Home >Backend Development >Golang >When to Use sync.Cond vs. Simple Locking: A Problem with sync.Cond and an Alternative Solution

When to Use sync.Cond vs. Simple Locking: A Problem with sync.Cond and an Alternative Solution

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 00:16:031053browse

When to Use sync.Cond vs. Simple Locking: A Problem with sync.Cond and an Alternative Solution

Troubleshooting Incorrect sync.Cond Usage

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:

  • Reevaluate the Need for sync.Cond: In this case, a simple sync.Mutex would suffice since there is only one writer (the downloader) and multiple readers (goroutines accessing headers).
  • 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn