Home >Backend Development >Golang >About golang read-write lock

About golang read-write lock

PHPz
PHPzforward
2020-09-25 14:18:473380browse

The following column golang tutorial will introduce to you about golang read-write locks. I hope it will be helpful to friends in need!

About golang read-write lock

golangRead-write lock, which is characterized by

  • read lock: multiple protocols can be performed at the same time Process read operations, no write operations are allowed

  • Write lock: Only one coroutine is allowed to perform write operations at the same time, and other write operations and read operations are not allowed

There are four methods for read-write locks

  • RLock: Acquire read lock

  • ##RUnLock: Release read lock

  • Lock: Acquire write lock

  • UnLock: Release write lock

Usage examples are as follows

package main

import (    "fmt"
    "sync"
    "time")var gRWLock *sync.RWMutexvar gVar intfunc init() {
    gRWLock = new(sync.RWMutex)
    gVar = 1}

func main() {    var wg sync.WaitGroup
    go Read(1, &wg)
    wg.Add(1)
    go Write(1, &wg)
    wg.Add(1)
    go Read(2, &wg)
    wg.Add(1)
    go Read(3, &wg)
    wg.Add(1)

    wg.Wait()
}

func Read(id int, wg *sync.WaitGroup) {
    fmt.Printf("Read Coroutine: %d start\n", id)
    defer fmt.Printf("Read Coroutine: %d end\n", id)
    gRWLock.RLock()
    fmt.Printf("gVar %d\n", gVar)
    time.Sleep(time.Second)
    gRWLock.RUnlock()

    wg.Done()

}

func Write(id int, wg *sync.WaitGroup) {
    fmt.Printf("Write Coroutine: %d start\n", id)
    defer fmt.Printf("Write Coroutine: %d end\n", id)
    gRWLock.Lock()
    gVar = gVar + 100
    fmt.Printf("gVar %d\n", gVar)
    time.Sleep(time.Second)
    gRWLock.Unlock()
    wg.Done()

}

The above is the detailed content of About golang read-write lock. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete