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

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

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮