duangangpin078794 2018-07-17 00:21
浏览 194
已采纳

Golang中的Broadcast()[关闭]

I am trying to use Broadcast() function from "sync" but it does not work as i wish to.

I need to lock execution for all of the goroutines and then simply by calling C.Broadcast() release them and let them execute but it is not happening.

How can i make it work?

This is everything what is written in docs **Broadcast wakes all goroutines waiting on *sync.Cond. **

Here is the code i am trying to make work:

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条回答 默认 最新

  • douya7282 2018-07-17 07:08
    关注

    As mentioned in the comments, the call to broadcast is probably happening before the goroutines get to C.Wait()

    You can fix this with another part of the sync package. A 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)
    }
    

    Also; it is not strictly necessary for you to hold the lock on M sync.Mutex when calling C.Broadcast()

    From the docs:

    It is allowed but not required for the caller to hold c.L during the call.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器