Home  >  Article  >  Backend Development  >  Go language document analysis: sync.Cond function implements condition variables

Go language document analysis: sync.Cond function implements condition variables

WBOY
WBOYOriginal
2023-11-04 15:15:30547browse

Go language document analysis: sync.Cond function implements condition variables

In the Go language, the sync package provides a very practical tool function - sync.Cond. This article provides a detailed analysis of this function and provides specific example code to help readers better understand and apply this function.

1. What is the sync.Cond function?

In the Go language, the sync.Cond function is used to implement condition variables. Condition variables are a commonly used synchronization mechanism in multi-threaded programming, used to achieve cooperation between threads when one or more threads need to wait for an event to occur. Specifically, when a certain condition is not met, the thread can enter the sleep state by waiting for the condition variable, and when the condition variable is met, other threads can cooperate by waking up the waiting thread in the condition variable.

The sync.Cond function is defined as follows:

type Cond struct {
    // contains filtered or unexported fields
}

sync.Cond is a structure type. Since it contains fields that are not exported, it cannot be initialized directly. When using it, we need to use the sync.NewCond function for initialization. The specific usage is as follows:

func NewCond(l Locker) *Cond

Among them, l is a mutex lock used to achieve synchronization between threads. After the initialization call, we need to use Cond's three main methods - Wait, Signal and Broadcast - to achieve cooperation between threads.

2. The main method of sync.Cond

  1. Wait

Wait method is used to make the current thread wait for the condition variable. Specifically, when a certain condition is not met, the thread can enter the sleep state by waiting for the condition variable and wait for other threads to wake up.

The definition of this method is as follows:

func (c *Cond) Wait()

When using the Wait method, we need to first acquire the mutex lock, release the lock before entering the waiting state, and wait for other threads to wake up and then reacquire it Lock.

The sample code is as follows:

package main

import (
    "fmt"
    "sync"
    "time"
)

var (
    wg      sync.WaitGroup
    locker  sync.Mutex
    condVar *sync.Cond
)

func main() {
    condVar = sync.NewCond(&locker)
    wg.Add(2)

    // 等待条件变量
    go func() {
        defer wg.Done()
        fmt.Println("wait for cond")
        condVar.L.Lock()
        condVar.Wait()
        fmt.Println("receive signal")
        condVar.L.Unlock()
    }()

    // 发送信号
    go func() {
        defer wg.Done()
        time.Sleep(2 * time.Second)
        condVar.L.Lock()
        condVar.Signal()
        fmt.Println("send signal")
        condVar.L.Unlock()
    }()

    wg.Wait()
}

In the above code, we first use the sync.NewCond function to initialize a mutex lock and its corresponding condition variable condVar. Then we use two concurrent goroutines to wait for the condition variable and send the signal respectively. The goroutine waiting for the condition variable first acquires the mutex lock and releases the lock before entering the waiting state. After waiting for the signal to be sent, the goroutine reacquires the lock and outputs relevant prompt information. The Go process that sends the signal acquires the mutex lock after waiting for two seconds, and releases the lock after sending a signal to the condition variable.

Run the above code, we can see that the program outputs the following content:

wait for cond
send signal
receive signal

It can be seen that the Go process waiting for the condition variable enters through the condVar.Wait method after waiting for a period of time. into sleep state. After the signal-sending Goroutine sends the signal, the Goroutine waiting for the condition variable is awakened through the condVar.Signal method, and the corresponding prompt information is returned.

  1. Signal

The Signal method is used to wake up a thread waiting for a condition variable. Specifically, when a certain condition variable changes, the thread can wake up one of the threads waiting for the condition variable through the Signal method to achieve cooperation between threads.

The definition of this method is as follows:

func (c *Cond) Signal()

It should be noted that the Signal method can only wake up a thread waiting for a condition variable. If we want to wake up multiple threads, we can use the Broadcast method.

The sample code is as follows:

package main

import (
    "fmt"
    "sync"
    "time"
)

var (
    wg      sync.WaitGroup
    locker  sync.Mutex
    condVar *sync.Cond
)

func main() {
    condVar = sync.NewCond(&locker)
    wg.Add(3)

    // 等待条件变量
    go func() {
        defer wg.Done()
        fmt.Println("wait for cond")
        condVar.L.Lock()
        condVar.Wait()
        fmt.Println("receive signal 1")
        condVar.L.Unlock()
    }()

    // 尝试多次等待
    go func() {
        defer wg.Done()
        for i := 0; i < 4; i++ {
            fmt.Printf("wait for cond %d
", i+1)
            condVar.L.Lock()
            condVar.Wait()
            fmt.Printf("receive signal %d
", i+1)
            condVar.L.Unlock()
        }
    }()

    // 发送信号
    go func() {
        defer wg.Done()
        time.Sleep(2 * time.Second)
        condVar.L.Lock()
        condVar.Signal()
        fmt.Println("send signal")
        condVar.L.Unlock()
        time.Sleep(2 * time.Second)
        condVar.L.Lock()
        condVar.Broadcast()
        fmt.Println("broadcast signal")
        condVar.L.Unlock()
    }()

    wg.Wait()
}

In the above code, we use three concurrent goroutines to wait for condition variables and send signals respectively. One of the goroutines uses the Wait method to wait for the condition variable, while the other goroutine tries to wait multiple times until the signal is received. The third goroutine first sends a signal after waiting for two seconds, and then waits for two seconds and then sends a broadcast signal again.

Run the above code, we can see that the program outputs the following content:

wait for cond
wait for cond 1
wait for cond 2
wait for cond 3
send signal
receive signal 1
wait for cond 4
broadcast signal
receive signal 2
receive signal 3
receive signal 4

It can be seen that the Go process waiting for the condition variable is first awakened and the corresponding prompt information is returned. The goroutine that then tried to wait multiple times waited and received the signal respectively. Finally, after sending the broadcast signal, all Goroutines waiting for the condition variable are awakened and the corresponding prompt information is returned.

3. Summary

This article briefly introduces the definition and main methods of the sync.Cond function in the Go language, provides a detailed analysis of its actual use, and gives specific example codes. When doing multi-thread programming, it is necessary to use condition variables rationally. Therefore, mastering the use of the sync.Cond function is of great help in improving the security and reliability of the code.

The above is the detailed content of Go language document analysis: sync.Cond function implements condition variables. 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