go runtime.Gosched()的作用分析

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

untime.Gosched()用於讓出CPU時間片。這就像跑接力賽,A跑了一會碰到代碼runtime.Gosched()就把接力棒交給B了,A歇著了,B繼續跑。

看代碼:

package main import ("fmt""runtime") func say(s string) {for i := 0; i < 2; i++ {runtime.Gosched()fmt.Println(s)}} func main() {go say("world")say("hello")}

 

輸出結果:

hello

world

hello

注意結果:

1、先輸出了hello,後輸出了world.

2、hello輸出了2個,world輸出了1個(因為第2個hello輸出完,主線程就退出了,第2個world沒機會了)

把代碼中的runtime.Gosched()注釋掉,執行結果是:

hello

hello

因為say("hello")這句佔用了時間,等它執行完,線程也結束了,say("world")就沒有機會了。

這裡同時可以看出,go中的goroutins並不是同時在運行。事實上,如果沒有在代碼中通過

runtime.GOMAXPROCS(n) 其中n是整數,

指定使用多核的話,goroutins都是在一個線程裡的,它們之間通過不停的讓出時間片輪流程執行,達到類似同時啟動並執行效果。

 

還需要學習一句話:

當一個goroutine發生阻塞,Go會自動地把與該goroutine處於同一系統線程的其他goroutines轉移到另一個系統線程上去,以使這些goroutines不阻塞

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.