代码之家  ›  专栏  ›  技术社区  ›  HowToGo

golang中的broadcast()[关闭]

  •  1
  • HowToGo  · 技术社区  · 7 年前

    我正在尝试使用来自“sync”的broadcast()函数,但它没有按我希望的方式工作。

    我需要锁定所有Goroutine的执行,然后通过调用c.broadcast()释放它们并让它们执行,但这并没有发生。

    我怎样才能让它工作?

    这就是在docs中编写的所有内容**broadcast唤醒等待*sync.cond的所有goroutine。**

    下面是我正在努力工作的代码:

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    var M sync.Mutex = sync.Mutex{}
    var C *sync.Cond = sync.NewCond(&M)
    
    func ff(){
        M.Lock()
        C.Wait()
        fmt.Println("broadcasting")
        M.Unlock()
    }
    
    func main() {
    
        num := [6]int{}
    
        for _, _= range num {
            go ff()
        }  
    
        M.Lock()
        C.Broadcast()
        M.Unlock()
    
        fmt.Println("done")
        time.Sleep(5 * time.Second)
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Zak    7 年前

    正如评论中提到的,广播呼叫可能在Goroutines到达之前发生。 C.Wait()

    你可以用 sync 包裹。一 WaitGroup

    package main
    
    import (
        "fmt"
        "sync"
        "time"
    )
    
    var M sync.Mutex
    var C *sync.Cond = sync.NewCond(&M)
    var wg sync.WaitGroup // create a wait group
    
    func ff(){
        wg.Done() // tell the group that one routine has started
        M.Lock()
        C.Wait()
        fmt.Println("broadcasting")
        M.Unlock()
    }
    
    func main() {
    
        num := [6]int{}
    
        wg.Add(len(num)) // tell the group you are waiting for len(num) goroutines to start
        for _, _= range num {
            go ff()
        }  
    
        M.Lock()
        wg.Wait() // wait for all the routines to start
        C.Broadcast()
        M.Unlock()
    
        fmt.Println("done")
        time.Sleep(5 * time.Second)
    }
    

    另外,你不必紧锁 M sync.Mutex 打电话时 C.Broadcast()

    从文档中:

    允许但不要求呼叫者在通话中保持C.L。

    https://golang.org/pkg/sync/#Cond