惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
J
Java Code Geeks
月光博客
月光博客
博客园_首页
The GitHub Blog
The GitHub Blog
Vercel News
Vercel News
B
Blog RSS Feed
博客园 - 聂微东
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
Jina AI
Jina AI
S
SegmentFault 最新的问题
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
Google DeepMind News
Google DeepMind News
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
量子位
Martin Fowler
Martin Fowler
博客园 - Franky
大猫的无限游戏
大猫的无限游戏
博客园 - 叶小钗

博客园 - 立志做一个好的程序员

【转】Golang使用时区时候报错 详解 Go 中的 rune 类型 【转】扫盲:Windows桌面应用开发框架:原生、跨平台、云桌面 Go-Zero自定义goctl实战:定制化模板,加速你的微服务开发效率 Go单体服务开发最佳实践 【转】Androidstudio报错Algorithm HmacPBESHA256 not available 借助ai来分析代码,理解代码 【转】linux设置密钥登录(只允许密钥登录) 【转】QPS和并发数的关系 【转】Command Pattern in Go (Golang) [转]Golang Functional Options Pattern 【转】Raft 理论基础 【转】spin lock 和mutex [转]Go sync.Once:简约而不简单的并发利器 [转]手把手教你如何用golang实现一个timewheel时间轮 [转]Golang线程池实现百万级高并发 [转]Go网络编程 · 一条TCP连接讲透九大知识点 【转】,接上面3篇.Implement Sql Database Driver in 100 Lines of Go 【转】dive into golang database/sql(3)
[转]Golang atomic.CompareAndSwapInt64()实例讲解
立志做一个好的程序员 · 2024-03-07 · via 博客园 - 立志做一个好的程序员

原文: http://www.manongjc.com/detail/30-anadyrrwgsoebxp.html

--------------

在Go语言中,原子包提供lower-level原子内存,这对实现同步算法很有帮助。 Go语言中的CompareAndSwapInt64()函数用于对int64值执行比较和交换操作。此函数在原子包下定义。在这里,您需要导入“sync/atomic”软件包才能使用这些函数。

用法:

func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)

在这里,addr表示地址,old表示int64值,它是从交换操作返回的旧交换值,而new则是int64新值,它将与旧交换值进行交换。

注意:(* int64)是指向int64值的指针。并且int64是位大小64的整数类型。此外,int64包含从-9223372036854775808到9223372036854775807的所有带符号的64位整数的集合。

返回值:如果交换完成,则返回true,否则返回false。

以下示例说明了上述方法的用法:

范例1:

// Golang Program to illustrate the usage of 
// CompareAndSwapInt64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  

输出:

Swapped:56677 , old value:686788787
true
The Value of i is: 908998

范例2:

// Golang Program to illustrate the usage of 
// CompareAndSwapInt64 function 
  
// Including main package 
package main 
  
// importing fmt and sync/atomic 
import ( 
    "fmt"
    "sync/atomic"
) 
  

输出:

Swapped:56677, old value:686788787
false
56677

在这里,CompareAndSwapInt64方法中的旧值必须是SwapInt64方法返回的交换值。此处不执行交换,因此返回false。