我正在尝试创建一个从事工作的工人线程池。
这似乎工作正常,但是如果我输入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
}
}
答案 0 :(得分:2)
将reader := bufio.NewReader(os.Stdin)
移动到for循环之前
我猜这是否会重复运行,stdin中的等待数据会丢失
答案 1 :(得分:1)
显然使该频道成为缓冲频道很有帮助。
jobs := make(chan string, 3)
谢谢大家