Home >Backend Development >Golang >Detailed explanation of the usage of mutex method in golang

Detailed explanation of the usage of mutex method in golang

PHPz
PHPzOriginal
2023-04-10 14:19:28989browse

mutex in golang is a method for multi-thread concurrency control. It is usually used to prevent multiple goroutines from accessing shared data at the same time. In this article, we will discuss mutex methods in golang.

  1. Definition of mutex

In golang, mutex is a structure type. Methods to access mutex include Lock method and Unlock method. When a goroutine calls the Lock method, it will occupy the mutex, thereby blocking access by other goroutines. When a goroutine completes its task and calls the Unlock method, it releases the mutex to allow other goroutines to access the shared resource. This mechanism ensures secure access to shared resources.

  1. Usage of mutex

The following is a basic usage example of mutex in golang program:

import "sync"
 
var mutex sync.Mutex
 
func main() {
    mutex.Lock()
    //执行你需要加锁的代码
    mutex.Unlock()
}

Using the above code, you can ensure that the execution There is only one goroutine that uses locked code. This effectively avoids data races and other thread safety issues.

  1. Example description

Now, let’s look at a more specific example of how mutex is used in golang.

import (
    "fmt"
    "sync"
    "time"
)
 
var mutex sync.Mutex
var wg sync.WaitGroup
var counter int
 
func worker(id int) {
    defer wg.Done()
 
    fmt.Printf("Worker %d starting\n", id)
    for i := 0; i < 5; i++ {
        mutex.Lock()
        time.Sleep(time.Millisecond)
        counter++
        fmt.Printf("Worker %d: %d\n", id, counter)
        mutex.Unlock()
    }
    fmt.Printf("Worker %d done\n", id)
}
 
func main() {
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go worker(i)
    }
 
    wg.Wait()
    fmt.Println("All workers are done")
}

In the above example, we used mutex to handle access to shared data. We defined a global variable named counter, and multiple goroutines call the worker function and try to modify the value of counter. mutex.Lock() will lock the shared variable and only one goroutine can access the variable. In each worker function, we increment counter by 1 and then print the result to show the current value of counter. Executing this program, you will see that the output is as expected, each counter value is incremented by 1, but only one goroutine can access the shared variable at a time.

  1. Summary

mutex is a powerful method in golang to ensure that multiple goroutines safely access shared resources. By controlling concurrent access through locking and unlocking between goroutines, we can avoid data races and other thread safety issues. In practice, to improve performance, we need to handle lock range and frequency appropriately. By properly using the mutex method, we can easily implement concurrency control and improve program execution efficiency.

The above is the detailed content of Detailed explanation of the usage of mutex method in golang. 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