How to safely obtain shared data in Goroutine?

PHPz
Release: 2024-06-04 17:37:01
Original
322 people have browsed it

In Go, the shared data of goroutine can be safely obtained through the following methods: 1. Mutex (Mutex): allows one goroutine to have exclusive access to shared data; 2. Channel (Channel): coordinates access to shared data and acts as a goroutine 3. Atomic Operation: read and modify shared variables atomically to ensure data consistency.

如何在 Goroutine 中安全地获取共享数据?

#How to safely obtain shared data in goroutine in Go?

In concurrent programming, coordinating access to shared data is crucial. The Go language provides several ways to achieve this, including mutexes, channels, and atomic operations.

Mutex lock

Mutex lock (Mutex) is used to allow one goroutine to access shared data at a time. To create a mutex, use the sync.Mutex type. The following is an example of how to use a mutex:

package main

import (
    "fmt"
    "sync"
)

// 共享变量
var counter int

func main() {
    var mu sync.Mutex

    // 创建 10 个 goroutine,每个 goroutine 增加 counter
    for i := 0; i < 10; i++ {
        go func() {
            mu.Lock()
            defer mu.Unlock()
            counter++
            fmt.Printf("goroutine %d: %d\n", i, counter)
        }()
    }
}
Copy after login

Channel

Channels can be used to pass data between goroutines and can also be used to coordinate access to shared data . To create a channel, you can use the make(chan) function. Here is an example of how to use channels:

package main

import (
    "fmt"
    "sync"
)

// 共享变量
var counter int

func main() {
    ch := make(chan struct{})

    // 创建 10 个 goroutine,每个 goroutine 增加 counter
    for i := 0; i < 10; i++ {
        go func() {
            defer close(ch)

            for {
                select {
                case <-ch:
                    return
                default:
                    counter++
                    fmt.Printf("goroutine %d: %d\n", i, counter)
                }
            }
        }()
    }

    // 等待所有 goroutine 完成
    for i := 0; i < 10; i++ {
        <-ch
    }
}
Copy after login

Atomic operations

Atomic operations can be used to atomically read and modify the value of a shared variable. The Go language provides the sync/atomic package to support atomic operations. Here is an example of how to use atomic operations:

package main

import (
    "fmt"
    "sync/atomic"
)

// 共享变量
var counter int

func main() {
    // 使用 AddInt64 增加 counter
    for i := 0; i < 10; i++ {
        go func() {
            atomic.AddInt64(&counter, 1)
            fmt.Printf("goroutine %d: %d\n", i, counter)
        }()
    }
}
Copy after login

Among these methods, which method to choose depends on the specific scenario and the required level of security assurance.

The above is the detailed content of How to safely obtain shared data in Goroutine?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!