How to synchronize random number generation in Golang parallel processing?

WBOY
Release: 2024-06-03 14:53:56
Original
313 people have browsed it

Synchronized random number generation in Go concurrent programming: Use a mutex (sync.Mutex) to control access to the rand.Rand random number generator. Each goroutine acquires the mutex before generating a random number and releases the mutex after generating it. This ensures that only one goroutine can access the random number generator at a time, eliminating data races.

如何在 Golang 并行处理中同步随机数生成?

How to synchronize random number generation in Golang parallel processing?

In Go concurrent programming, it is sometimes necessary to generate random numbers across multiple goroutines. If synchronization is not taken care of, this can lead to race conditions and unpredictable behavior.

Parallel random number generation

Go provides a math/rand package to generate pseudo-random numbers. By default, it operates in a non-concurrency-safe manner. This means that if the same rand.Rand instance is accessed concurrently, data races and indeterminate results will occur.

Synchronization using mutex

To synchronize random number generation in parallel processing, you can use a mutex (sync.Mutex). A mutex allows only one goroutine to access the critical section at a time (in this case, the rand.Rand instance).

The following code demonstrates how to use a mutex lock to synchronize random number generation:

package main

import (
    "math/rand"
    "sync"
)

var (
    // 全局互斥锁
    randomLock sync.Mutex
    
    // 全局随机数生成器
    randomGen *rand.Rand
)

func init() {
    // 在程序启动时初始化随机数生成器
    // 并设置随机种子
    randomGen = rand.New(rand.NewSource(time.Now().UnixNano()))
}

func main() {
    // 创建一个等待组来跟踪 goroutine
    var wg sync.WaitGroup
    
    // 启动 10 个 goroutine 生成 10 个随机数
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go func(i int) {
            // 使用互斥锁保护随机数生成
            randomLock.Lock()
            value := randomGen.Intn(100)
            randomLock.Unlock()
            
            // 打印生成的随机数
            fmt.Printf("Goroutine %d: %d\n", i, value)
            wg.Done()
        }(i)
    }

    // 等待所有 goroutine 完成
    wg.Wait()
}
Copy after login

In this method, a global randomLock mutex is used to protect the pairrandomGen Access to the random number generator. Each goroutine acquires the mutex before generating a random number and releases the mutex after generating it. This ensures that only one goroutine has access to the random number generator at a time, eliminating data races.

In this way, random numbers can be generated safely and reliably in parallel processing.

The above is the detailed content of How to synchronize random number generation in Golang parallel processing?. 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!