網(wǎng)站首頁 編程語言 正文
無緩沖channel的內(nèi)存泄漏問題:無緩沖channel在go程里done <- hardWork(job)時,如果外層執(zhí)行完了后,done <- hardWork(job)寫操作<- 會一直阻塞
func requestWork(ctx context.Context, job interface{}) error {
ctx, cancel := context.WithTimeout(ctx, time.Second*2)
defer cancel()
done := make(chan error)
go func() {
done <- hardWork(job)
}()
select {
case err := <-done:
return err
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
const total = 1000
var wg sync.WaitGroup
wg.Add(total)
now := time.Now()
for i := 0; i < total; i++ {
go func() {
defer wg.Done()
requestWork(context.Background(), "any")
}()
}
wg.Wait()
fmt.Println("elapsed:", time.Since(now))
time.Sleep(time.Minute*2)
fmt.Println("number of goroutines:", runtime.NumGoroutine())
}
? go run timeout.go elapsed: 2.005725931s number of goroutines: 1001
原文鏈接:https://blog.csdn.net/qq_34562093/article/details/122180380
相關(guān)推薦
- 2022-07-10 Executor 線程池技術(shù)詳解
- 2023-04-08 Python中關(guān)于?*args與**args的用法及說明_python
- 2022-05-06 C#反射機制介紹_C#教程
- 2022-03-03 uniapp的報錯ncaught Error: Module build failed (from
- 2023-02-07 Pytorch中的廣播機制詳解(Broadcast)_python
- 2023-03-13 Go語言中GORM存取數(shù)組/自定義類型數(shù)據(jù)_Golang
- 2022-08-04 pandas添加新列的5種常見方法_python
- 2022-10-05 帶你深度走入C語言取整以及4種函數(shù)_C 語言
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支