golang并发编程-模式

发布时间 2023-03-30 10:08:40作者: 北京涛子

1. Generator


9. Queue

package main

import (
    "fmt"
    "sync"
    "time"
)

const limit = 4
const work = 100

func process(wg *sync.WaitGroup, work int, queue chan struct{}) {
    queue <- struct{}{}

    go func() {
        defer wg.Done()

        time.Sleep(time.Second * 1)
        fmt.Println("processed: ", work)

        <-queue
    }()
}

func main() {
    var wg sync.WaitGroup

    fmt.Println("Queue limit: ", limit)
    queue := make(chan struct{}, limit)

    wg.Add(work)
    for w := 0; w < work; w++ {
        process(&wg, w, queue)
    }

    wg.Wait()
    close(queue)
    fmt.Println("work complete")
}