網(wǎng)站首頁 編程語言 正文
正文
最近在學通道channel,發(fā)現(xiàn)一個簡單的demo:
package main import "fmt" func main() { chanInt := make(chan int) go func() { chanInt <- 100 }() res := <-chanInt fmt.Println(res) }
輸出結果是100,這個沒有問題。但是之前在學goroutine的時候有看到過一個例子:
package main import "fmt" func hello() { fmt.Println("Hello Goroutine!") } func main() { go hello() // 啟動另外一個goroutine去執(zhí)行hello函數(shù) fmt.Println("main goroutine done!") }
這個例子輸出的只有:main goroutine done! 并沒有Hello Goroutine!
看過解釋:在程序啟動時,Go程序就會為main()函數(shù)創(chuàng)建一個默認的goroutine。當main()函數(shù)返回的時候該goroutine就結束了,所有在main()函數(shù)中啟動的goroutine會一同結束
那么這個解釋放到第一個例子為什么不適用了?
ps:我得理解是:運行到res := <-chanInt這句會阻塞,直到協(xié)程寫入通道后,就馬上讀取,繼續(xù)執(zhí)行打印語句。不知道理解的對不對?
然后就是關于阻塞的情況,比如我把第一個例子改一下:
package main import ( "fmt" "time" ) func main() { chanInt := make(chan int) go func() { chanInt <- 100 }() time.Sleep(10 * time.Second) res := <-chanInt fmt.Println(res) }
多了time.Sleep(10 * time.Second)等待10秒鐘,10秒后輸出100,這個沒有問題。
然后再看一個例子:
func main() { chanInt := make(chan int) chanInt <- 100 res := <-chanInt fmt.Println(res) }
原文鏈接:https://segmentfault.com/q/1010000040414910
相關推薦
- 2022-05-21 Python學習之包與模塊詳解_python
- 2023-02-26 flutter實現(xiàn)掃碼槍獲取數(shù)據(jù)源禁止系統(tǒng)鍵盤彈窗示例詳解_Android
- 2022-08-19 InnoDB 事務
- 2022-04-11 python文件讀寫操作小結_python
- 2022-03-20 docker中容器數(shù)據(jù)卷volume介紹_docker
- 2023-01-28 GoLang?nil與interface的空指針深入分析_Golang
- 2022-07-03 Golang之理解錯誤輸出
- 2022-04-28 淺析python中特殊文件和特殊函數(shù)_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支