小编Eag*_*eNN的帖子

使用通道同步多个goroutine

我需要使用单个任务队列和单个结果队列来启动多个工作程序。每个工人都应该在不同的goroutine中启动。我需要等到所有工作人员都将完成并且任务队列将为空后再退出程序。我准备了goroutine同步的小例子。主要思想是我们将排队的任务计数,并等待所有工人完成工作。但是当前的实现有时会遗漏值。为什么会发生这种情况以及如何解决问题?示例代码:

import (
    "fmt"
    "os"
    "os/signal"
    "strconv"
)

const num_workers = 5

type workerChannel chan uint64

// Make channel for tasks
var workCh workerChannel
// Make channel for task counter
var cntChannel chan int

// Task counter
var tskCnt int64

// Worker function
func InitWorker(input workerChannel, result chan string, num int) {
    for {
        select {
        case inp := <-input:
            getTask()
            result <- ("Worker " + strconv.Itoa(num) + ":" + strconv.FormatUint(inp, 10))
        }
    }
}

// Function to manage task …
Run Code Online (Sandbox Code Playgroud)

concurrency synchronization channel go goroutine

3
推荐指数
1
解决办法
1391
查看次数

标签 统计

channel ×1

concurrency ×1

go ×1

goroutine ×1

synchronization ×1