gpt4 book ai didi

go - 当 GOMAXPROCS 为 1 时是否需要加锁

转载 作者:IT王子 更新时间:2023-10-29 00:51:10 25 4
gpt4 key购买 nike

The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously.

因此,如果 GOMAXPROCS 为 1,无论我有多少个 goroutine,都可以安全地从不同的 goroutine 访问变量(如 map)而无需任何锁定。正确吗?

最佳答案

简短的回答是,“不”它不安全。冗长的答案确实太长,无法在此处进行足够详细的解释,但我将提供一个简短的摘要和一些文章链接,这些文章应该可以帮助您将各个部分放在一起。

让我们先区分“并发”和“并行”。考虑两个函数。并行运行,它们可以同时在不同的处理器上执行。同时运行其中一个,或两者同时运行,或者两者都可能正在执行,但两者都能够执行。如果它们是并发的但不是并行的,那么它们正在切换——如果没有 channel 或锁,我们无法保证先到先得的顺序。

“并发而不并行”想想可能很奇怪,但反之想想就很不起眼,并行但不并发;我的文本编辑器、终端和浏览器都在并行运行,但绝对不是并发的。

因此,如果两个(或 20,000 个)函数可以访问同一内存,比如说一个写入一个读取,并且它们同时运行,那么写入可能先发生,读取可能先发生。除非我们负责调度/排序,因此没有锁和 channel ,否则没有任何保证。

将 GOMAXSPROCS 设置为大于 1 可以使并发程序并行运行,但也可能不是,所有 concurrent goroutines 可能在一个 CPU 线程上,也可能在多个 CPU 线程上。因此,将 GOMAXPROCS 设置为 1 并不能保证并发进程在没有锁或 channel 来协调其执行的情况下是安全的。

线程[通常]由操作系统调度。参见 Wikipedia或者你最喜欢的人类知识库。 Goroutines 由 Go 调度。

接下来考虑这个:

Even with [a] single logical processor and operating system thread, hundreds of thousands of goroutines can be scheduled to run concurrently with amazing efficiency and performance.

还有这个:

The problem with building concurrency into our applications is eventually our goroutines are going to attempt to access the same resources, possibly at the same time. Read and write operations against a shared resource must always be atomic. In other words reads and writes must happen by one goroutine at a time or else we create race conditions in our programs.

来自 this article ,它很好地解释了差异并引用了一些您可能想要查找的其他 Material (该文章有些过时,因为 GMAXPROCS 不再默认为 1,但一般理论仍然准确)。

最后,Effective Go 刚开始时可能会令人望而生畏,但却是一本必读的书。 Here是Go中并发的解释。

关于go - 当 GOMAXPROCS 为 1 时是否需要加锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37391009/

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