go - Golang 中的广播()

标签 go synchronization

<分区>

我正在尝试使用“同步”中的 Broadcast() 函数,但它无法正常工作。

我需要锁定所有 goroutine 的执行,然后简单地通过调用 C.Broadcast() 释放它们并让它们执行,但它没有发生。

我怎样才能让它发挥作用?

这就是文档中写的所有内容 **广播唤醒所有等待 *sync.Cond 的 goroutines。 **

这是我正在努力使工作的代码:

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)
}

最佳答案

如评论中所述,对广播的调用可能发生在 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)
}

还有;在调用 C.Broadcast()

时,您不一定需要锁定 M sync.Mutex

来自文档:

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

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

关于go - Golang 中的广播(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51371587/

相关文章:

google-app-engine - 如何使用 Go 从 Google App Engine 的模型中删除字段?

pointers - 无法通过结构方法替换指针

ios - 同步更新 UITableView 的模式?

c# - 如何同步SQLServer数据库和MySQL数据库

go - 是否可以使用GoLang调试预构建的go可执行文件?

go - 如何使 template.Execute() 写入文件而不是 response.Writer?

google-app-engine - 在 Travis 中编译 App Engine 应用程序

Mysql同步关系型数据库

go - 确保值仅被检索一次

C++ 线程,共享数据