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, 程序正常運行。
package main import ( "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有機會運行
但是會發(fā)生死鎖, 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 main import ( "fmt" //"time" ) func main() { go func1() go func2() select { } } func func1() { fmt.Println("here1") } func func2() { fmt.Println("here2") }
3. 第三種情況, 正常運行
package main import ( "fmt" ) var c = make(chan int, 2) func main() { go func1() go func2() <-c <-c fmt.Println("ok") } func func1() { fmt.Println("here1") c <- 1 } func func2() { fmt.Println("here2") c <- 1 }
4. 實現(xiàn)上面的目的的另外一種方法:
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()
補充:golang中死鎖的情況分析
Golang關于channel死鎖情況的匯總以及解決方案
直接讀取空channel的死鎖
當一個channel中沒有數(shù)據(jù),而直接讀取時,會發(fā)生死鎖:
func main() { q := make(chan int, 2) <-q }
錯誤提示:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
main.main()
/home/erick/Desktop/Book/Parallel/final.go:159 +0x4d
exit status 2
上述代碼中,創(chuàng)建了一個2個容量的channel,直接讀取發(fā)生了死鎖情況。
修正方案,使用select方法阻止,在default中放置默認處理方式:
func main() { q := make(chan int, 2) select { case v := <-q: fmt.Println(v) default: fmt.Println("nothing in channel") } }
輸出:
nothing in channel
過度寫入數(shù)據(jù)造成的死鎖
寫入數(shù)據(jù)超過channel的容量,也會造成死鎖:
func main() { q := make(chan int, 2) q <- 1 q <- 2 q <- 3 }
解決方案,與寫入的方式一樣,使用select方法阻止,在default中放置默認處理方式:
func main() { q := make(chan int, 2) q <- 1 q <- 2 select { case q <- 3: fmt.Println("ok") default: fmt.Println("wrong") } }
向已經(jīng)關閉的channel中寫入數(shù)據(jù)
這種造成的不是死鎖,而是產(chǎn)生panic。
func main() { q := make(chan int, 2) close(q) q <- 1 }
代碼錯誤:
panic: send on closed channel
goroutine 1 [running]:
main.main()
/home/erick/Desktop/Book/Parallel/final.go:154 +0x63
exit status 2
解決方案:只有別向已經(jīng)關閉的channel寫數(shù)據(jù)。。。。
但是,可以從已經(jīng)關閉的channel中讀取數(shù)據(jù):
func main() { q := make(chan int, 3) q <- 1 q <- 2 q <- 3 close(q) for v := range q { fmt.Println(v) }
下面開始講解goroutine的讀寫
package main import "fmt" func main() { c:=make(chan string) go func() { c<-"hello" }() fmt.Println(<-c) }
上面這個是對的
package main import "fmt" func main() { c:=make(chan string) fmt.Println(<-c) go func() { c<-"hello" }() }
上面這個是錯的,會發(fā)生死鎖,因為程序會阻塞在fmt.Println(<-c),并不會向下執(zhí)行。在該行發(fā)生了阻塞,以致于下面的代碼沒有機會執(zhí)行。因此可以總結(jié)寫在讀前,寫操作完成后才有讀操作。
總結(jié):
上述提到的死鎖,是指在程序的主線程中發(fā)生的情況,如果上述的情況發(fā)生在非主線程中,讀取或者寫入的情況是發(fā)生堵塞的,而不是死鎖。
實際上,阻塞情況省去了我們加鎖的步驟,反而是更加有利于代碼編寫,要合理的利用阻塞。。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章
最新版Golang?pprof使用詳解(引入、抓取、分析,圖文結(jié)合)
這篇文章主要介紹了最新版Golang?pprof使用詳解包括引入、抓取、分析,圖文結(jié)合,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-08-08Go-ethereum?解析ethersjs中產(chǎn)生的簽名信息思路詳解
這篇文章主要介紹了Go-ethereum?解析ethersjs中產(chǎn)生的簽名信息,我們解析簽名的需要知道,簽名的消息,簽名,和公鑰,按照這個思路,我們可以通過ethers實現(xiàn)消息的簽名,也可以通過go-ethereum實現(xiàn),需要的朋友可以參考下2022-08-08詳解如何在Go中循環(huán)中使用Defer關鍵字示例詳解
這篇文章主要為大家介紹了詳解如何在Go中循環(huán)中使用Defer關鍵字示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09Go Resiliency庫中timeout實現(xiàn)原理及源碼解析
Go-Resiliency庫中的timeout是一種基于協(xié)程的超時機制,通過創(chuàng)建協(xié)程來執(zhí)行任務并設置超時時間,若任務執(zhí)行時間超時則中止協(xié)程并返回錯誤,需要詳細了解可以參考下文2023-05-05Golang發(fā)送Get和Post請求的實現(xiàn)
做第三方接口有時需要用Get或者Post請求訪問,本文主要介紹了Golang發(fā)送Get和Post請求的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-05-05goframe重寫FastAdmin后端實現(xiàn)實例詳解
這篇文章主要為大家介紹了goframe重寫FastAdmin后端實現(xiàn)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12淺析Golang如何向已關閉的chan讀寫數(shù)據(jù)
這篇文章主要為大家詳細介紹了Golang如何向已關閉的chan讀寫數(shù)據(jù),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02詳解Golang利用反射reflect動態(tài)調(diào)用方法
這篇文章主要介紹了詳解Golang利用反射reflect動態(tài)調(diào)用方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-11-11