Home  >  Article  >  Backend Development  >  Go concurrent programming: the use of channels and synchronization primitives

Go concurrent programming: the use of channels and synchronization primitives

PHPz
PHPzOriginal
2024-06-05 09:03:57733browse

To sum up, channels and synchronization primitives in Go are crucial tools in concurrent programming. Channels are used to safely exchange data, while synchronization primitives are used to control the concurrent execution of Goroutines. Specifically, channels allow Goroutines to pass data, mutexes protect shared resources, condition variables wait for conditions to be true, and events are used to synchronize Goroutines. By using these mechanisms, developers can create efficient and scalable concurrent applications.

Go concurrent programming: the use of channels and synchronization primitives

Go concurrent programming: the use of channels and synchronization primitives

The channels and synchronization primitives in Go are used to implement concurrent programming key tool. This article will explore the use of both mechanisms and demonstrate their power through practical examples.

Channel

Channel is a mechanism used to safely exchange data between concurrent Goroutines. It is similar to a pipe, data can be written from one end and read from the other end.

// 声明一个用于传递整数的通道
channel := make(chan int)

// 在一个 Goroutine 中写入通道
go func() {
    channel <- 42
}()

// 在另一个 Goroutine 中读取通道
value := <-channel

Synchronization primitives

Synchronization primitives are a series of tools used to control concurrent Goroutine execution. They include things like locks, mutexes, condition variables, and events.

Mutex lock

Mutex lock is used to ensure that only one Goroutine accesses shared resources at the same time.

// 声明一个互斥锁
var mu sync.Mutex

// 在一个 Goroutine 中使用互斥锁保护共享资源
func incrementCounter() {
    mu.Lock()
    defer mu.Unlock()
    counter++
}

Conditional variable

Conditional variable is used to wait for a certain condition to be true. Goroutine can wait for a condition variable until the condition is met before continuing execution.

// 声明一个条件变量
var cv sync.Cond

// 在一个 Goroutine 中等待条件
func waitForCondition() {
    cv.L.Lock()
    for !condition {
        cv.Wait()
    }
    cv.L.Unlock()
}

// 在另一个 Goroutine 中唤醒等待条件的 Goroutine
func signalCondition() {
    cv.L.Lock()
    condition = true
    cv.Broadcast()
    cv.L.Unlock()
}

Practical case

Using channels to process tasks in parallel

A common concurrency problem is parallel processing tasks. This problem can be solved by creating a set of Goroutines that compute the results and put the results into a channel.

// 生成任务列表
tasks := []func() int{
    func() int { return 1 },
    func() int { return 2 },
    func() int { return 3 },
}

// 创建一个通道来接收结果
results := make(chan int)

// 创建 Goroutine 来计算任务
for _, task := range tasks {
    go func(task func() int) {
        results <- task()
    }(task)
}

// 从通道中接收结果
for i := 0; i < len(tasks); i++ {
    result := <-results
    fmt.Println(result)
}

Using mutexes to protect shared state

Another common concurrency problem is protecting shared state. This problem can be solved by using a mutex to ensure that only one Goroutine accesses the shared state at the same time.

// 声明共享状态变量
var sharedState int

// 创建一个互斥锁来保护共享状态
var mu sync.Mutex

// 在一个 Goroutine 中读取共享状态
func readSharedState() int {
    mu.Lock()
    defer mu.Unlock()
    return sharedState
}

// 在另一个 Goroutine 中写共享状态
func writeSharedState(value int) {
    mu.Lock()
    defer mu.Unlock()
    sharedState = value
}

The above is the detailed content of Go concurrent programming: the use of channels and synchronization primitives. 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