[英]Wait on main thread with sleep in goroutine
編寫了此非常基本的代碼以了解渠道。
如果goroutine中有等待,為什么主goroutine正在等待它? 我讀到主goroutine需要等待一段時間,因為調用goroutine之后,控件立即被傳遞回給它。
為什么goroutine不能像Java中的主線程和子線程那樣設計為可以並行運行?
func main() {
channel := make(chan int)
go func() {
time.Sleep(3*time.Second)
}()
for {
fmt.Println("../");
<-channel
}
}
我認為您的主線程正在等待來自渠道的消息
func main() {
channel := make(chan int)
go func() {
time.Sleep(3*time.Second)
channel <- 1 // Sending something to the channel to let the main thread continue
channel <- 2
}()
for {
fmt.Println("../");
<-channel // Waiting for something to come from the channel
}
}
關於您的特定問題:
如果goroutine中有等待,為什么主goroutine正在等待它?
它不等待,可能正在通道中等待。
我讀到主goroutine需要等待一段時間,因為調用goroutine之后,控件立即被傳遞回給它。
如果您的主程序不在通道上等待(或處於無限循環中的堆棧),則它已經完成並關閉了應用程序。 GoRoutines用主線程關閉(例如Java守護程序線程)
為什么goroutine不能像Java中的主線程和子線程那樣設計為可以並行運行?
他們實際上是這樣做的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.