Home > Backend Development > Golang > Lock application in concurrent programming in Go language

Lock application in concurrent programming in Go language

王林
Release: 2024-03-24 10:21:03
Original
614 people have browsed it

Lock application in concurrent programming in Go language

Go language is an open source programming language originally developed by Google to improve programmer efficiency and system performance. The Go language supports concurrent programming, which means executing multiple tasks at the same time. The use of locks is a common way to ensure concurrency safety. In this article, we will explore how to use locks in the Go language to ensure the correctness of concurrent programs and give specific code examples.

Why locks are needed

In concurrent programming, when multiple goroutines (lightweight threads in Go language) access shared variables or resources at the same time, race conditions (Race Condition). Race conditions can lead to data inconsistency and even program crashes. In order to avoid this situation from happening, we need to use locks to control and protect shared resources.

Mutex (Mutex)

Mutex is the most common type of lock. Mutex can ensure that only one goroutine can access shared resources at the same time. In the Go language, you can use the Mutex type in the sync package to implement a mutex lock.

The following is a simple sample code:

package main

import (
    "fmt"
    "sync"
)

var (
    balance int
    mu      sync.Mutex
)

func deposit(amount int) {
    mu.Lock()
    defer mu.Unlock()
    balance += amount
}

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

    fmt.Println("Final balance:", balance)
}
Copy after login

In the above code, we define a global variable balance to represent the account balance, and a mutex lockmu is used to protect access to balance. The deposit function is responsible for depositing the amount into the account. During the deposit process, you need to call mu.Lock() to lock it, and then call mu.Unlock(() after the operation is completed. ) to unlock.

In the main function, start 1000 goroutines to perform deposit operations concurrently, wait for all goroutines to be executed through sync.WaitGroup, and finally print out the final account balance.

Read-write lock (RWMutex)

In addition to mutex locks, the Go language also provides read-write locks (RWMutex) to achieve scenarios where more reading is done and less writing is done. Read-write locks allow multiple goroutines to read shared resources at the same time, but will block all read operations when there are write operations.

The following is a sample code using a read-write lock:

package main

import (
    "fmt"
    "sync"
)

var (
    data map[string]string
    mu   sync.RWMutex
)

func readData(key string) string {
    mu.RLock()
    defer mu.RUnlock()
    return data[key]
}

func writeData(key, value string) {
    mu.Lock()
    defer mu.Unlock()
    data[key] = value
}

func main() {
    data = make(map[string]string)
    var wg sync.WaitGroup
    for i := 0; i < 100; i++ {
        wg.Add(1)
        go func() {
            for j := 0; j < 1000; j++ {
                key := fmt.Sprintf("key%d", j)
                value := fmt.Sprintf("value%d", j)
                writeData(key, value)
                fmt.Println(readData(key))
            }
            wg.Done()
        }()
    }
    wg.Wait()
}
Copy after login

In the above code, we define a data variable as a shared data storage, and a Read-write lock mu is used to protect concurrent access to data. The readData function is used to read the data of the specified key, calling mu.RLock() for read locking; the writeData function is used to write key-value data, Call mu.Lock() for write locking.

In the main function, start 100 goroutines to concurrently perform read and write operations, and print each read data through fmt.Println. Using read-write locks can improve the concurrency performance of the program and ensure that reading operations of data are not blocked by writing operations.

Summary

Through the introduction of this article, we understand the importance of using locks in concurrent programming in Go language, and how to use mutex locks and read-write locks to protect shared resources and avoid competition. occurrence of state conditions. In actual development, reasonable use of locks can improve the concurrency performance of the program and ensure the correctness of the program. I hope this article can help readers better understand the application of locks in concurrent programming in Go language.

The above is the detailed content of Lock application in concurrent programming in Go language. For more information, please follow other related articles on the PHP Chinese website!

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