首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的Golang Workerpool忽略作业?

为什么我的Golang Workerpool忽略作业?
EN

Stack Overflow用户
提问于 2018-09-24 21:58:47
回答 2查看 103关注 0票数 2

我正在尝试创建一个工作人员的线程池。

这似乎工作得很好,但如果我,例如,输入1-6。它不会打印出六个。

有没有人能解释一下原因,希望能为我提供一个解决方案?

代码语言:javascript
复制
// 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
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-09-27 03:31:52

显然,将通道设置为缓冲通道很有帮助。

代码语言:javascript
复制
jobs := make(chan string, 3)

谢谢你们

票数 1
EN

Stack Overflow用户

发布于 2018-09-25 03:11:48

reader := bufio.NewReader(os.Stdin)移到for循环之前

我猜想如果重复运行,stdin中的等待数据就会丢失。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52481054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档