• golang读写锁RWMutex


    读写锁是针对读写的互斥锁

    基本遵循两大原则:

    1、可以随便读,多个goroutine同时读

    2、写的时候,啥也不能干。不能读也不能写

    RWMutex提供了四个方法:

    func (*RWMutex) Lock // 写锁定

    func (*RWMutex) Unlock // 写解锁

    func (*RWMutex) RLock // 读锁定

    func (*RWMutex) RUnlock // 读解锁

    一、随便读

    package main
    
    import (
        "sync"
        "time"
    )
    
    var m *sync.RWMutex
    
    func main() {
        m = new(sync.RWMutex)
        
        // 多个同时读
        go read(1)
        go read(2)
    
        time.Sleep(2*time.Second)
    }
    
    func read(i int) {
        println(i,"read start")
    
        m.RLock()
        println(i,"reading")
        time.Sleep(1*time.Second)
        m.RUnlock()    
    
        println(i,"read over")
    }

    运行结果:

    1 read start

    1 reading 

    2 read start

    2 reading

    1 read over

    2 read over

    可以看出1 读还没有结束,2已经在读

    二、写的时候啥也不能干

    package main
    
    import (
        "sync"
        "time"
    )
    
    var m *sync.RWMutex
    
    func main() {
        m = new(sync.RWMutex)
        
        // 写的时候啥也不能干
        go write(1)
        go read(2)
        go write(3)
    
        time.Sleep(2*time.Second)
    }
    
    func read(i int) {
        println(i,"read start")
    
        m.RLock()
        println(i,"reading")
        time.Sleep(1*time.Second)
        m.RUnlock()    
    
        println(i,"read over")
    }
    
    func write(i int) {
        println(i,"write start")
    
        m.Lock()
        println(i,"writing")
        time.Sleep(1*time.Second)
        m.Unlock()
    
        println(i,"write over")
    }

    输出:

    1 write start

    1 writing

    2 read start

    3 write start

    1 writing over

    2 reading

    2 read over

    3 writing

    3 write over

  • 相关阅读:
    2.16 C++类与new和delete操作符
    2.15 C++常量指针this
    2.14 C++析构函数
    2.13 C++拷贝构造函数
    2.12 C++ explicit关键字详解
    2.11 C++转型构造函数
    2.10 C++利用构造函数限制对象的创建
    2.9 C++使用默认参数的构造函数
    2.8 C++参数初始化表
    linux 查看进程启动路径
  • 原文地址:https://www.cnblogs.com/ExMan/p/15246140.html
Copyright © 2020-2023  润新知