How to correctly use sync.Cond?

前端 未结 8 809
忘了有多久
忘了有多久 2021-02-01 16:11

I\'m having trouble figuring out how to correctly use sync.Cond. From what I can tell, a race condition exists between locking the Locker and invoking the condition\'s Wait meth

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 16:58

    In the excellent book "Concurrency in Go" they provide the following easy solution while leveraging the fact that a channel that is closed will release all waiting clients.

    package main
    import (
        "fmt"
        "time"
    )
    func main() {
        httpHeaders := []string{}
        headerChan := make(chan interface{})
        var consumerFunc= func(id int, stream <-chan interface{}, funcHeaders *[]string)         
        {
            <-stream
            fmt.Println("Consumer ",id," got headers:", funcHeaders )   
        }
        for i:=0;i<3;i++ {
            go consumerFunc(i, headerChan, &httpHeaders)
        }
        fmt.Println("Getting headers...")
        time.Sleep(2*time.Second)
        httpHeaders=append(httpHeaders, "test1");
        fmt.Println("Publishing headers...")
        close(headerChan )
        time.Sleep(5*time.Second)
    }
    

    https://play.golang.org/p/cE3SiKWNRIt

提交回复
热议问题