gpt4 book ai didi

go - 何时以及为什么使用 go 的 atomic 包比较 =,+

转载 作者:行者123 更新时间:2023-12-01 22:33:53 25 4
gpt4 key购买 nike

As go 的文档说明:

The add operation, implemented by the AddT functions, is the atomic equivalent of:

*addr += delta

return *addr

The load and store operations, implemented by the LoadT and StoreT functions, are the atomic equivalents of "return *addr" and "*addr = val".


这是我的问题:
为什么我应该使用“atomic.AddT”而不是“+”?
为什么 'atomic.LoadT' 不是 '=' ?
'=' 和 '+' 不是异常的吗?
谁能给我一个显示它们之间差异的例子?

最佳答案

首先,你需要了解 go memory 模型:

https://golang.org/ref/mem

要理解的关键点是,goroutine 中变量写入的影响不一定对另一个 goroutine 可见,就像写入 goroutine 观察它们的方式一样。也就是说,如果一个 goroutine 将一个值写入变量 a然后到另一个变量b ,另一个 goroutine 可能会以未指定的顺序看到这些写入。这就是为什么您需要像 channel 或互斥锁这样的并发原语。在 channel 操作或互斥操作之前发生的任何事情都将在此时对所有 goroutine 可见。

原子操作提供了类似的保证,尽管内存模型没有明确指定。

使用原子编写代码并不容易。您必须考虑所有可能的执行交错​​以确保没有竞争。坚持使用 channel 和互斥锁。正确的代码比快速但活泼的代码要好。

关于go - 何时以及为什么使用 go 的 atomic 包比较 =,+,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62442460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com