gpt4 book ai didi

go - 它是并发的,但是什么使其可以并行运行?

转载 作者:行者123 更新时间:2023-12-03 10:09:45 29 4
gpt4 key购买 nike

因此,我在尝试学习Go的同时试图理解并行计算的工作原理。我了解并发性和并行性之间的区别,但是,我有点坚持的是Go(或OS)如何确定应并行执行某件事...
编写代码时我需要做些什么,还是全部由调度程序处理?
在下面的示例中,我有两个函数,分别使用go关键字在单独的Go例程中运行。因为默认的GOMAXPROCS是您机器上可用的处理器数量(并且我也在显式设置它),所以我希望这两个函数可以同时运行,因此输出将是特定顺序的数字混合-并且此外,每次运行时输出都会不同。然而,这种情况并非如此。相反,它们在一个接一个地运行,并且使事情更加困惑,第二个功能在第一个功能之前运行。
代码:

func main() {
runtime.GOMAXPROCS(6)
var wg sync.WaitGroup
wg.Add(2)

fmt.Println("Starting")
go func() {
defer wg.Done()
for smallNum := 0; smallNum < 20; smallNum++ {
fmt.Printf("%v ", smallNum)
}
}()

go func() {
defer wg.Done()
for bigNum := 100; bigNum > 80; bigNum-- {
fmt.Printf("%v ", bigNum)
}
}()

fmt.Println("Waiting to finish")
wg.Wait()

fmt.Println("\nFinished, Now terminating")
}
输出:
go run main.go
Starting
Waiting to finish
100 99 98 97 96 95 94 93 92 91 90 89 88 87 86 85 84 83 82 81 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Finished, Now terminating
我正在关注本文,尽管我遇到的几乎每个示例都具有类似的功能。
Concurrency, Goroutines and GOMAXPROCS
这是应该的工作方式,我没有正确理解某些内容,还是我的代码不正确?

最佳答案

Is there something I have to do when writing my code,


不。

or is it all handled by the schedulers?


是的。

In the example below, I have two functions that are run in separate Go routines using the go keyword. Because the default GOMAXPROCS is the number of processors available on your machine (and I'm also explicitly setting it) I would expect that these two functions run at the same time


他们可能会或可能不会,您在这里没有控制权。

and thus the output would be a mix of number in particular order - And furthermore that each time it is run the output would be different. However, this is not the case. Instead, they are running one after the other and to make matters more confusing function two is running before function one.


是的。同样,您不能强制并行计算。
您的测试有缺陷:您在每个goroutine中都不做太多事情。在您的示例中,goroutine 2可能被安排为运行,开始运行并在goroutine 1开始运行之前完成。使用 go“启动” goroutine不会强制它立即开始执行,所有要做的就是创建一个可以运行的新goroutine。所有可以运行的goroutine都会安排在您的处理器上。所有这些调度都无法控制,它是全自动的。如您所知,这是并发与并行之间的区别。您可以控制Go中的并发性,但不能(在很多方面)控制在两个或多个内核上实际并行执行的操作。
使用实际的,长期运行的goroutine进行实际工作的更实际的示例将显示交错的输出。

关于go - 它是并发的,但是什么使其可以并行运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64462255/

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