Initial Problem Outline:
An attempt to use sync.Cond results in a race condition, causing an immediate panic due to a deadlock. The developer suspects an issue between locking the Mutex and invoking the condition's Wait method.
Clarification of the Intended Use Case:
Apart from the race condition, the primary goal is to create a synchronization mechanism where multiple goroutines wait for HTTP headers to become available from a long-running downloading goroutine.
Resolution:
Example with Multiple Readers and One Writer:
var sharedRsc = make(map[string]interface{}) func main() { var wg sync.WaitGroup wg.Add(2) m := sync.Mutex{} c := sync.NewCond(&m) go func() { c.L.Lock() for len(sharedRsc) == 0 { c.Wait() } fmt.Println(sharedRsc["rsc1"]) c.L.Unlock() wg.Done() }() go func() { c.L.Lock() for len(sharedRsc) == 0 { c.Wait() } fmt.Println(sharedRsc["rsc2"]) c.L.Unlock() wg.Done() }() c.L.Lock() sharedRsc["rsc1"] = "foo" sharedRsc["rsc2"] = "bar" c.Broadcast() c.L.Unlock() wg.Wait() }
Alternative Solution:
If using channels is feasible in this situation, it is still the preferred method for passing data around.
The above is the detailed content of When to Use sync.Cond vs. Simple Locking: A Problem with sync.Cond and an Alternative Solution. For more information, please follow other related articles on the PHP Chinese website!