官术网_书友最值得收藏!

Goroutines aren't predictable

In this chapter, we started by looking at how Go enables us to write code that is concurrent and, to an extent, parallel. Then we followed up with a discussion on how Go schedules goroutines over machines and processors. It is possible that we might be able to reason how the goroutines are going to be distributed over machines and processors, which in turn might let us write non-standard or hacky Go code.

Consider the code from the Parallelism section, where we tried to simulate listening to music while writing a few emails. Here is the output of the code for quick reference:

Done writing mail #3. 19:32:57
Listening... 19:32:57
Listening... 19:32:57
Done writing mail #1. 19:32:57
Listening... 19:32:57
Listening... 19:32:57
Done writing mail #2. 19:32:57

We can now easily infer that there were at least two Ps, and one of them was being used by the goroutine printing Listening..., while the other P was handling the goroutines related to writing emails.

This is all well and good, however consider the case where GOMAXPROCS is set to 1 or the system has low hardware capabilities which might result in fewer machines. It is possible that this might lead to the goroutine printing Listening... run forever and never giving control to the other goroutines. In reality, the Go compiler should detect this case and accordingly plan the scheduling of goroutines. However, it would be better to plan our code so that we do not have to rely on Go's scheduler and its current implementation.

主站蜘蛛池模板: 柘荣县| 湖口县| 九江市| 玉山县| 尼木县| 曲沃县| 茶陵县| 玉门市| 瑞昌市| 宜兴市| 连平县| 敖汉旗| 余干县| 北安市| 日照市| 鄢陵县| 上栗县| 平舆县| 合肥市| 商城县| 乐山市| 汝南县| 鄂尔多斯市| 南阳市| 鲁山县| 武义县| 天镇县| 图片| 固安县| 乐清市| 拉萨市| 高邮市| 太白县| 大埔区| 郯城县| 藁城市| 兖州市| 昌吉市| 莱阳市| 蚌埠市| 东乌|