How to use Cond in Go language
This article mainly explains "the use of Cond in Go language". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "the use of Cond in Go language".
Cond in Golang's sync package implements a conditional variable, which is mainly used to solve the scenario in which multiple read cooperators wait for shared resources to become ready. When using Cond, you need to pay special attention to: each Cond will be associated with a Lock (* sync.Mutex or * sync.RWMutex). When you modify the condition or call the Wait method, you must lock it to protect the condition.
1. Introduction of Cond:
The definition is as follows:
Cond related API introduction, Cond is mainly composed of three functions, Broadcast (), Signal (), Wait ().
1.1. Broadcast ()
Used to wake up all co-routines that are waiting for c, and if there is no waiting co-program, this function will not report an error.
Note: when using this function, it can be unlocked or locked, because the function does not modify the operation.
1.2. Signal ()
Notify a single co-program waiting for c state to continue execution, and if there are more than one co-program waiting at this time, the first one waiting will be taken from the waiting list to receive the message.
Note: when using this function, you can also leave it unlocked, as shown in reason 1.1.
1.3. Wait ()
It mainly consists of four steps:
Unlock ()->
Blocking waiting for notification (that is, waiting for notification of Signal () or Broadcast ())->
Receive notification->
Lock ()
After the function is called, the co-program is in a blocking state until it is notified by Signal or Broadcast.
Note: when using this function, be sure to add a lock.
two。 Examples
2.1. Example of cooperation between broadcast and wait
Result analysis: from the output results, we can see that coroutines 0 and 1 in the wait state will continue to perform subsequent operations after receiving the broadcast.
2.2. Example of cooperation between signal and wait
Result analysis: as can be seen from the output result, when the first signal is triggered, even if there are already two cooperators in the wait state, the first waiting co-program 0 in the wait state will be called first.
Co-program 1, which is in a waiting state, will not be called until the second sinal is triggered.
Reference documentation:
Https://ieevee.com/tech/2019/06/15/cond.html
Https://golang.org/pkg/sync/#Cond
Https://cyent.github.io/golang/goroutine/sync_cond/
Thank you for reading, the above is the content of "the use of Cond in Go language". After the study of this article, I believe you have a deeper understanding of the use of Cond in Go language, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!