Home  >  Article  >  Backend Development  >  Use the sync.Mutex function in golang to implement concurrency-safe code

Use the sync.Mutex function in golang to implement concurrency-safe code

WBOY
WBOYOriginal
2023-11-18 13:01:02510browse

Use the sync.Mutex function in golang to implement concurrency-safe code

Use the sync.Mutex function in golang to implement concurrency-safe code

In concurrent programming, when multiple goroutines access shared variables at the same time, data may occur competitive situation. In order to ensure the consistency and correctness of data, we can use mutex locks (Mutex) to implement concurrency-safe code.

Golang provides the sync package, which contains the Mutex type. Through the Mutex's Lock() and Unlock() methods, we can lock and unlock before and after access to the shared resources that need to be protected.

Below we use a simple code example to demonstrate how to use sync.Mutex to implement concurrency-safe code.

package main

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

var (
    count int
    mutex sync.Mutex
)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 10; i++ {
        wg.Add(1)
        go increment(&wg)
    }
    wg.Wait()

    fmt.Println("Final count:", count)
}

func increment(wg *sync.WaitGroup) {
    mutex.Lock()
    defer mutex.Unlock()

    time.Sleep(time.Millisecond) // 模拟一些耗时操作

    count++
    wg.Done()
}

In the above code, we define a global variable count and a mutex lock mutex. 10 goroutines are created in the main function, and each goroutine calls the increment function.

In the increment function, first call mutex.Lock() to obtain the mutex lock, and then perform some operations on shared resources that need to be protected. Here we simulate a time-consuming operation to increase the complexity of the code. Finally call mutex.Unlock() to release the mutex lock.

As the number of goroutines increases, operations on count will become shared resources for concurrent access. By using a mutex lock, we ensure that only one goroutine can access and modify the count variable at the same time, thus avoiding data competition.

Finally, wait for all goroutines to be executed through sync.WaitGroup, and then output the final count value.

Through the mutex lock, we realize concurrent safe access to count, ensuring the consistency and correctness of the operation.

It should be noted that mutex locks should be used with caution. Excessive use of mutexes will reduce parallel performance and easily introduce deadlocks and other problems. When writing concurrent programs, you should minimize access to shared variables and use more lightweight concurrency primitives (such as atomic operations or channels) to avoid overuse of mutexes.

To summarize, using the sync.Mutex function in golang can achieve concurrency-safe code. By locking the read and write operations of shared resources, we ensure the consistency and correctness of data access between different goroutines. However, in actual applications, we should use locks carefully according to specific situations to avoid problems such as performance degradation and deadlock.

The above is the detailed content of Use the sync.Mutex function in golang to implement concurrency-safe code. 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