打破常规思维
自由 开放 平等 互助

goroutine/Channel WaitGroup等待任务结束

package main

import (
    "fmt"
    "sync"
)

func doWorker(id int, w worker) {
    for n := range w.in {
        fmt.Printf("Worker %d received %c\n", id, n)
        w.done()
    }
}

type worker struct {
    in   chan int
    done func()
}

func createWorker(id int, wg *sync.WaitGroup) worker {
    w := worker{
        in: make(chan int),
        done: func() {
            wg.Done()
        },
    }

    // Worker
    go doWorker(id, w)
    return w
}

func chanDemo() {
    var workers [10]worker
    var wg sync.WaitGroup

    // 初始化worker
    for i, _ := range workers {
        workers[i] = createWorker(i, &wg)
    }
    wg.Add(20)

    // 任务1
    for i, worker := range workers {
        worker.in <- 'a' + i
    }

    // 任务2
    for i, worker := range workers {
        worker.in <- 'A' + i
    }

    wg.Wait()
}

func main() {
    chanDemo()
}

 

赞(0) 打赏
未经允许不得转载:时光日记 » goroutine/Channel WaitGroup等待任务结束

评论 抢沙发

评论前必须登录!

 

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏