golang coroutine 的等待與死結

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

直接上代碼:

1. 第一種情況, 如果沒有select{}, main 主線程不會等待coroutine運行,導致coroutine得不到機會運行。

You are requesting eventual scheduling (using the two go statements) 
of two goroutines and then you exit main without giving the scheduler 
a chance to do anything. 

有了select, 程式正常運行。

package mainimport ("fmt"        "time")func main() {go func1()go func2()select{}}func func1() {       for{    fmt.Println("here1")            time.Sleep(10 * time.Minute)        }}func func2() {       for{   fmt.Println("here2")           time.Sleep(10 * time.Minute)       }
}

2. coroutine有機會運行,但是會發生死結, fatal error: all goroutines are asleep - deadlock!

The goroutine executing func1 exited, ditto for func2. The main goroutine is blocked with no hope to recover while no other goroutine can be scheduled.

package mainimport ("fmt"//"time")func main() {go func1()go func2()select {}}func func1() {fmt.Println("here1")}func func2() {fmt.Println("here2")}


3. 第三種情況, 正常運行。

package mainimport ("fmt")var c = make(chan int, 2)func main() {go func1()go func2()<-c<-cfmt.Println("ok")}func func1() {fmt.Println("here1")c <- 1}func func2() {fmt.Println("here2")c <- 1}

4. 實現上面的目的的另外一種方法:

  var wg sync.WaitGroup    var urls = []string{            "http://www.golang.org/",            "http://www.google.com/",            "http://www.somestupidname.com/",    }    for _, url := range urls {            // Increment the WaitGroup counter.            wg.Add(1)            // Launch a goroutine to fetch the URL.            go func(url string) {                    // Decrement the counter when the goroutine completes.                    defer wg.Done()                    // Fetch the URL.                    http.Get(url)            }(url)    }    // Wait for all HTTP fetches to complete.    wg.Wait()


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.