【发布时间】:2017-07-08 12:42:13
【问题描述】:
我正在尝试打印一组大作业(“1,2”、“3,4”、“5”)与额外作业(“一”、“二”、“三”)和使用 Goroutines 和 Workgroups 来做到这一点。
我期待以下输出(不完全按此顺序,但内部工作组应先于外部工作组完成):
Big Job being done: 1,2
1_one
1_two
1_three
2_one
2_two
2_three
Big Job 1,2 is Done!
Big Job being done: 3,4
3_one
3_two
3_three
4_one
4_two
4_three
Big Job 3,4 is Done!
Big Job being done: 5
5_one
5_two
5_three
Big Job 5 is Done!
All Big Jobs are done!
去游乐场链接:https://play.golang.org/p/Hvbcmw06WY
但是,当我运行我的代码时,我会得到以下输出:
Big job 1,2 is Done!
Big job 3,4 is Done!
Big job 5 is Done!
Big Job being done: 5
5_three
Big Job being done: 1,2
1_three
Big Job being done: 3,4
3_three
5_one
5_two
1_one
1_two
3_one
3_two
fatal error: all goroutines are asleep - deadlock!
如您所见,Big Jobs 的第二部分(2 和 4)不知何故“丢失”在 goroutine 中。
此外,All Big Jobs are done! 消息永远不会到达,因为所有 goroutine 都以某种方式进入睡眠状态,即使每个 Waitgroup 应该已经完成(尽管缺少的 2 和 4 部分可能与它有关)。
我还注意到,出于某种原因,Done 消息首先被打印(尽管我假设 Print 函数只是无法赶上 Goroutines)。
这是我想要完成的非 Goroutine 版本:https://play.golang.org/p/zZpfyIbbn8
知道我做错了什么吗?
【问题讨论】:
-
操场上的代码有很多问题......首先检查你应该使用 goroutines 的文档......它们同时是安全的......你不应该需要更多一个等待组..我认为您的代码需要重新组织...并且可能通过频道进行控制。也不要在 goroutine 中创建等待组。附件是您的代码的略微修改版本,不会恐慌。 play.golang.org/p/gBQPUGNvNb 它不会有你寻找的打印顺序,因为 goroutine 是异步的。所以你可能想要创建一个缓冲队列
标签: go synchronization goroutine