我正在尝试创建一个工作人员的线程池。
这似乎工作得很好,但如果我,例如,输入1-6。它不会打印出六个。
有没有人能解释一下原因,希望能为我提供一个解决方案?
// Golang Workerpool
func worker(id int, jobs <-chan string) {
fmt.Println("Worker", id, "initilized!")
for {
s := <- jobs
time.Sleep(2 * time.Second)
fmt.Println("Worker", id, "said:", s);
}
}
func main() {
// In order to use our pool of workers we need to send
// them work and collect their results. We make 2
// channels for this.
jobs := make(chan string)
// This starts up 3 workers, initially blocked
// because there are no jobs yet.
for w := 1; w <= 3; w++ {
go worker(w, jobs)
}
for {
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('\n')
jobs <- text
}
}
发布于 2018-09-27 03:31:52
显然,将通道设置为缓冲通道很有帮助。
jobs := make(chan string, 3)
谢谢你们
发布于 2018-09-25 03:11:48
将reader := bufio.NewReader(os.Stdin)
移到for循环之前
我猜想如果重复运行,stdin中的等待数据就会丢失。
https://stackoverflow.com/questions/52481054
复制相似问题