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

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