Home  >  Article  >  Backend Development  >  How is the lock in golang function implemented?

How is the lock in golang function implemented?

PHPz
PHPzOriginal
2024-06-05 12:39:57993browse

The locks in the Go language implement synchronized concurrent code to prevent data competition: Mutex: Mutex lock, ensuring that only one goroutine acquires the lock at the same time, used for critical section control. RWMutex: Read-write lock, which allows multiple goroutines to read data at the same time, but only one goroutine can write data at the same time. It is suitable for scenarios that require frequent reading and writing of shared data.

How is the lock in golang function implemented?

#How are locks implemented in Go functions?

In Go, locks are mainly used to synchronize concurrent code and prevent data competition caused by concurrent access. The Go language provides multiple types of locks, each with different characteristics and usage scenarios.

sync.Mutex: Mutex lock

Mutex lock is the most basic lock, which guarantees that only one goroutine can acquire the lock at the same time. Use Mutex to control access to critical sections.

package main

import (
    "fmt"
    "sync"
)

var counter int
var mutex sync.Mutex

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 500; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            mutex.Lock()
            counter++
            fmt.Printf("Counter: %d\n", counter)
            mutex.Unlock()
        }()
    }
    wg.Wait()
}

sync.RWMutex: Read-write lock

Read-write lock allows multiple goroutines to read data at the same time, but only allows one goroutine to write data at the same time. This is very useful for scenarios that require frequent reading and writing of shared data.

package main

import (
    "fmt"
    "sync"
)

type BankAccount struct {
    balance int
    sync.RWMutex
}

func (b *BankAccount) Deposit(amount int) {
    b.Lock()
    defer b.Unlock()
    b.balance += amount
}

func (b *BankAccount) Withdraw(amount int) {
    b.Lock()
    defer b.Unlock()
    b.balance -= amount
}

func (b *BankAccount) Balance() int {
    b.RLock()
    defer b.RUnlock()
    return b.balance
}

func main() {
    var wg sync.WaitGroup
    bankAccount := BankAccount{balance: 100}

    for i := 0; i < 500; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            bankAccount.Deposit(10)
        }()
    }

    for i := 0; i < 500; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            bankAccount.Withdraw(10)
        }()
    }

    fmt.Println(bankAccount.Balance())
    wg.Wait()
}

The above is the detailed content of How is the lock in golang function implemented?. 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