Learn Sync.Cond in Golang

Tram Ho

  • By definition, event is any signal between two or more goroutine that actually occurred. Usually you will want one to wait for a signal before executing another goroutine. If we consider to do this without using Cond then simply use an endless loop.

  • This workaround is also good, but really won’t work, because you have to figure out how long it takes to configure the sleep function. If sleep is too long, it will affect performance, and if it is too short, it will waste CPU time unnecessarily. It would be nice if there was some kind of function or something where goroutine could sleep until a signal executes. And Cond will help enforce that.

functions in cond:

  • NewCond:

  • Broadcast

  • Signals:

  • Wait:

  • Use Cond to write a simple example first:

  • This approach is more efficient. Note, the Wait func not only blocks, it also suspends the current goroutine , and allows other goroutines to still run on OS thread .
  • For further explanation, see also the following example:

  • output:

  • As a result, the program has added 10 items to the queue, but it always waits for one item to be dequeue before enqueue another item.
  • In the example there is a Signal function, which is a method that Cond provides to notify a goroutine that was blocked on a previous wait.
Share the news now

Source : Viblo