Conditional variables in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

GoThe Language Sync package provides the conditional variable ( condition variable ) type:

type Cond struct {        // L is held while observing or changing the condition        L Locker        // contains filtered or unexported fields}type Cond    func NewCond(l Locker) *Cond    func (c *Cond) Broadcast()    func (c *Cond) Signal()    func (c *Cond) Wait()type Lockertype Locker interface {        Lock()        Unlock()}A Locker represents an object that can be locked and unlocked.

NewCond()The function input parameter is an Locker interface type, which is a variable that implements the lock function. The Broadcast() function notifies all the condition variable waiting goroutine , and the Signal() function notifies only one of them goroutine . Wait()will let goroutine the block in condition variable , wait for the condition to set up. The usual practice is to:

c.L.Lock()for !condition() {    c.Wait()}... make use of condition ...c.L.Unlock()

Wait()the entry function will unlock and the Wait() function will be unlocked again. Due to the logic of re-locking in "unlock-and-Receive notifications", it is possible that another same wait() goroutine preemptive step changes the condition, causing goroutine the current condition to cease to be true, so this block uses loop detection. Refer to the following example:

package mainimport (    "sync"    "time"    "fmt")func main() {    c := sync.NewCond(&sync.Mutex{})    var num int    for i := 1; i <= 2; i++ {        go func(id int) {            fmt.Println("Enter Thread ID:", id)            c.L.Lock()            for num != 1 {                fmt.Println("Enter loop: Thread ID:", id)                c.Wait()                fmt.Println("Exit loop: Thread ID:", id)            }            num++            c.L.Unlock()            fmt.Println("Exit Thread ID:", id)        }(i)    }    time.Sleep(time.Second)    fmt.Println("Sleep 1 second")    num++    c.Broadcast()    time.Sleep(time.Second)    fmt.Println("Program exit")}

The results of one execution are as follows:

Enter Thread ID: 2Enter loop: Thread ID: 2Enter Thread ID: 1Enter loop: Thread ID: 1Sleep 1 secondExit loop: Thread ID: 2Exit Thread ID: 2Exit loop: Thread ID: 1Enter loop: Thread ID: 1Program exit

As can be seen from the above example, due to goroutine 2 the change of conditions, leading to goroutine 1 re-enter the cycle, that is, multiple goroutine blocking in one condition variable of the existence of a competitive relationship.

Resources:
Package sync;
Condition Variables.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.