惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
T
Threatpost
阮一峰的网络日志
阮一峰的网络日志
美团技术团队
F
Fortinet All Blogs
The GitHub Blog
The GitHub Blog
月光博客
月光博客
V
Visual Studio Blog
T
Tailwind CSS Blog
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
Jina AI
Jina AI
J
Java Code Geeks
Martin Fowler
Martin Fowler
大猫的无限游戏
大猫的无限游戏
Recorded Future
Recorded Future
C
Check Point Blog
腾讯CDC
N
Netflix TechBlog - Medium
aimingoo的专栏
aimingoo的专栏
罗磊的独立博客
Hacker News: Ask HN
Hacker News: Ask HN
SecWiki News
SecWiki News
博客园 - Franky
Hacker News - Newest:
Hacker News - Newest: "LLM"
N
News | PayPal Newsroom
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Security @ Cisco Blogs
W
WeLiveSecurity
The Last Watchdog
The Last Watchdog
Cloudbric
Cloudbric
F
Full Disclosure
The Cloudflare Blog
Y
Y Combinator Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
MongoDB | Blog
MongoDB | Blog
S
Schneier on Security
Schneier on Security
Schneier on Security
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
AI
AI
N
News and Events Feed by Topic
T
Tor Project blog
P
Palo Alto Networks Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
H
Hackread – Cybersecurity News, Data Breaches, AI and More
G
Google Developers Blog

博客园 - 斌哥tobin

Go工程选择开源分库分表中间件可用性测试 Laravel Model查询结果的3种存储格式内存占用对比 Laravel配置Route调用artisan 研究微信红包分配算法之Golang版 解决IDEA提示Untrusted Server's certificate 证书不可用( Server's certificate is not trusted ) select * 和 select 字段的速度对比 Docker镜像拉取失败或超时的解决办法:添加国内镜像 php连接docker运行的mysql,显示(HY000/2002): Connection refused的解决办法 VirtualBox虚拟CentOS7共享文件夹 Windows7用VirtualBox虚拟Ubuntu共享文件夹的终极方式 PhpStorm添加PHP代码规范检查CodeSniffer(phpcs)和PHP代码静态分析工具Mess Detector(phpmd) php的三个常用判断函数 php计算字符串长度 mac brew 安装php扩展报错:parent directory is world writable but not sticky Mac iTerm2命令行快捷操作 System.Web.AspNetHostingPermission 类型的权限已失败 优化phpstorm运行卡顿问题! composer [ReflectionException] Class Fxp\Composer\AssetPlugin\Repository\NpmRepository does not exist - 斌哥tobin nginx1.8安装nginx_concat_module及400错误解决办法
Golang解决fatal error: all goroutines are asleep - deadlock!
斌哥tobin · 2021-07-14 · via 博客园 - 斌哥tobin

2021-07-14 23:22  斌哥tobin  阅读(1670)  评论()    收藏  举报

今天进行一个协程操作demo时总是报错

//workerpool.go
package main

import (
	"fmt"
	"time"
)

//工作线程
func workerPool(jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Println("start job", j)
		time.Sleep(time.Second) //模拟耗时工作
		fmt.Println("finish job", j)
		results <- j
	}
}

func main() {
	const numJobs = 5
	jobs := make(chan int, numJobs)    //
	results := make(chan int, numJobs) //

	go workerPool(jobs, results)

	for i := 1; i <= numJobs; i++ {
		jobs <- i
	}
        close(jobs)
        for r := range results {
		fmt.Println("results :", r)
	}
}

go run workerpool.go 报错

start job 1
finish job 1
start job 2
results : 1
finish job 2
start job 3
results : 2
finish job 3
start job 4
results : 3
finish job 4
start job 5
results : 4
finish job 5
fatal error: all goroutines are asleep - deadlock!
results : 5

goroutine 1 [chan receive]:
main.main()
	workerpool.go:30 +0x19d

asleep就是说协程都在睡觉没做事
问题应该出在遍历jobs上, jobs遍历完没数据可操作了,引发 asleep - deadlock 报错
改进方法:
1、是无限循环输入数据到jobs
2、用waitGroup

方法1的无限循环输入数据就不做介绍了,比较简单
下面展示一下方法2使用waitGroup的方式


package main

import (
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

//工作线程
func workerPool(jobs <-chan int, results chan<- int) {
	for j := range jobs {
		fmt.Println("start job", j)
		time.Sleep(time.Second)
		fmt.Println("finish job", j)
		results <- j
	}
}

func init() {
	wg = sync.WaitGroup{}
}

func main() {
	const numJobs = 5
	jobs := make(chan int)    //
	results := make(chan int) //

	go workerPool(jobs, results)
	go func() {
		for r := range results {
			fmt.Println("results :", r)
			wg.Done()//接收到数据,表示完成了一份工作
		}
	}()

	for i := 1; i <= numJobs; i++ {
		wg.Add(1)//标记开始一份工作
		jobs <- i
	}

	wg.Wait()

}

正常运行结果如下:
start job 1
finish job 1
start job 2
results : 1
finish job 2
start job 3
results : 2
finish job 3
start job 4
results : 3
finish job 4
start job 5
results : 4
finish job 5
results : 5

Process finished with exit code 0