douhuan1257 2018-09-24 13:58
浏览 46
已采纳

为什么我的Golang Workerpool忽略工作?

I am trying to create a threadpool of workers that do jobs.

This seems to working fine, but it if I, for instance, input 1-6. It won't print out six.

Can someone explain why and hopefully provide a fix for me?

// 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('
')
        jobs <- text
    }
}
  • 写回答

2条回答 默认 最新

  • douxuan4556 2018-09-26 19:31
    关注

    Apparently making the channel a buffered channel helped.

    jobs := make(chan string, 3)
    

    Thanks guys

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c