加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang 原子操作函数

发布时间:2020-12-16 09:31:18 所属栏目:大数据 来源:网络整理
导读:golang中的原子操作在sync/atomic package中。 下文以比较和交换操作函数为例,介绍其使用。 CompareAndSwapInt32 比较和交换操作是原子性的。 // CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value.func CompareAndSwapInt3

golang中的原子操作在sync/atomic package中。

下文以比较和交换操作函数为例,介绍其使用。

CompareAndSwapInt32

比较和交换操作是原子性的。

// CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value.
func CompareAndSwapInt32(addr *int32,old,new int32) (swapped bool)

判断参数addr指向的值是否与参数old的值相等,
如果相等,用参数new的新值替换掉addr存储的旧值,否则操作就会被忽略。

交换成功,返回true.

example1

package main

import (
        "fmt"
        "sync/atomic"
)

func main(){

        var value int32

        fmt.Println("origin value:",value)

        swapFlag := atomic.CompareAndSwapInt32(&value,1)

        if swapFlag {
                fmt.Println("swap,value:",value)
        } else {
                fmt.Println("not swap,value)
        }

}

上面的代码是简单使用举例。
判断value中的值是否为0,如果是,则将1存储到value的地址中;否则,不做任何操作。

output:

origin value: 0
swap,value: 1

examaple2

下面例子中,有两个goroutine去更新同一地址存储的值,只有一个会操作成功。

package main

import (
        "fmt"
        "sync/atomic"
        "time"
)

func main(){
        var value int32
        fmt.Println("origin value:",value)

        go entry("1",&value)

        go entry("2",&value)

        time.Sleep(time.Second)
}

func entry(name string,value *int32) {

        swapFlag := atomic.CompareAndSwapInt32(value,1)

        if swapFlag {
                fmt.Println("goroutine name:",name,",swap,*value)
        } else {
                fmt.Println("goroutine name:",not swap,*value)
        }

}

创建两个goroutine,两个goroutine执行相同的流程,同时去更新value。
其中一个会操作成功。

主goroutine等待两个goroutine结束。

output:

origin value: 0
goroutine name: 2,value: 1
goroutine name: 1,value: 1

参考

https://www.kancloud.cn/digest/batu-go/153537
http://ifeve.com/go-concurrency-atomic/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读