登录
首页 >  Golang >  Go问答

为何我的 Golang Workerpool 不执行任务?

来源:stackoverflow

时间:2024-03-01 11:54:25 278浏览 收藏

怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《为何我的 Golang Workerpool 不执行任务?》,涉及到,有需要的可以收藏一下

问题内容

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

这似乎工作正常,但如果我输入 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
    }
}

解决方案


reader := bufio.newreader(os.stdin) 移至 for 循环之前

我猜如果重复运行,标准输入中的等待数据就会丢失

显然使通道成为缓冲通道有帮助。

jobs := make(chan string, 3)

谢谢大家

以上就是《为何我的 Golang Workerpool 不执行任务?》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>