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

About golang read-write lock

PHPz
Release: 2020-09-25 14:19:01
forward
3405 people have browsed it

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()

}
Copy after login

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!

Related labels:
source:cnblogs.com
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