gpt4 book ai didi

Goroutines 不能并行工作

转载 作者:数据小太阳 更新时间:2023-10-29 03:28:25 26 4
gpt4 key购买 nike

给定以下代码:

package main

import (
"fmt"
"runtime"
"time"
)


func f(from string) {

for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
//runtime.Gosched()
}
}

func main() {

runtime.GOMAXPROCS(runtime.NumCPU()*2)
time.Sleep(100)

go f("i am not parallel")

go f("neither me")

var input string
fmt.Scanln(&input)
}

大多数情况下的输出是:

i am not parallel : 0
i am not parallel : 1
i am not parallel : 2
neither me : 0
neither me : 1
neither me : 2

有时:

neither me : 0
neither me : 1
neither me : 2
i am not parallel : 0
i am not parallel : 1
i am not parallel : 2

runtime.Gosched() 取消注释时,一切似乎都正常。我尝试将 GOMAXPROCS 数量从 2 更改为 NumCPU、goroutines 数量、周期:没有一个可以让它并行工作。
为什么会有如此奇怪的行为?

编辑:好的,似乎上下文切换是一项繁重的工作,并且在没有合理的情况下不会经常进行。有一件事我仍然无法理解 - 为什么人们 get it to work没有任何 sleep 说明?

最佳答案

你不应该预测 goroutine 的时间表。通过运行您提供的示例,我得到了这个输出。

direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
goroutine : 2
going
done

如果我在 main 函数的开头添加 runtime.GOMAXPROCS(4),并在我的 i5 Qcore 桌面 ubuntu 上运行它,它会输出

direct : 0
direct : 1
direct : 2
goroutine : 0
goroutine : 1
goroutine : 2
going

done

我认为它并不总是产生相同的输出。所以我们应该假设 goroutine 可以并行,如果你需要控制顺序加锁。

关于Goroutines 不能并行工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31285215/

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