[Golang]Coroutine可能存在的死锁

前端之家收集整理的这篇文章主要介绍了[Golang]Coroutine可能存在的死锁前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


直接上代码

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, 程序正常运行。

  1. packagemain
  2. import(
  3. "fmt"
  4. "time"
  5. )
  6. funcmain(){
  7. gofunc1()
  8. gofunc2()
  9. select{}
  10. }
  11. funcfunc1(){
  12. for{
  13. fmt.Println("here1")
  14. time.Sleep(10*time.Minute)
  15. }
  16. }
  17. funcfunc2(){
  18. for{
  19. fmt.Println("here2")
  20. time.Sleep(10*time.Minute)
  21. }
}
 

2. coroutine有机会运行,但是会发生死锁,fatal error: all goroutines are asleep - deadlock!

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

  1. packagemain
  2. import(
  3. "fmt"
  4. //"time"
  5. )
  6. funcmain(){
  7. gofunc1()
  8. gofunc2()
  9. select{
  10. }
  11. }
  12. funcfunc1(){
  13. fmt.Println("here1")
  14. }
  15. funcfunc2(){
  16. fmt.Println("here2")
  17. }


3. 第三种情况, 正常运行。

  1. packagemain
  2. import(
  3. "fmt"
  4. )
  5. varc=make(chanint,2)
  6. funcmain(){
  7. gofunc1()
  8. gofunc2()
  9. <-c
  10. <-c
  11. fmt.Println("ok")
  12. }
  13. funcfunc1(){
  14. fmt.Println("here1")
  15. c<-1
  16. }
  17. funcfunc2(){
  18. fmt.Println("here2")
  19. c<-1
  20. }

4. 实现上面的目的的另外一种方法

  1. varwgsync.WaitGroup
  2. varurls=[]string{
  3. "http://www.golang.org/",
  4. "http://www.google.com/",
  5. "http://www.somestupidname.com/",
  6. }
  7. for_,url:=rangeurls{
  8. //IncrementtheWaitGroupcounter.
  9. wg.Add(1)
  10. //LaunchagoroutinetofetchtheURL.
  11. gofunc(urlstring){
  12. //Decrementthecounterwhenthegoroutinecompletes.
  13. deferwg.Done()
  14. //FetchtheURL.
  15. http.Get(url)
  16. }(url)
  17. }
  18. //WaitforallHTTPfetchestocomplete.
  19. wg.Wait()
原文链接:https://www.f2er.com/go/190544.html

猜你在找的Go相关文章