golang 中 sync.Mutex 和 sync.RWMutex

介绍

golang 中的 sync 包实现了两种锁:

  • Mutex:互斥锁
  • RWMutex:读写锁,RWMutex 基于 Mutex 实现

Mutex(互斥锁)

  • Mutex 为互斥锁,Lock() 加锁,Unlock() 解锁
  • 在一个 goroutine 获得 Mutex 后,其他 goroutine 只能等到这个 goroutine 释放该 Mutex
  • 使用 Lock() 加锁后,不能再继续对其加锁,直到利用 Unlock() 解锁后才能再加锁
  • 在 Lock() 之前使用 Unlock() 会导致 panic 异常
  • 已经锁定的 Mutex 并不与特定的 goroutine 相关联,这样可以利用一个 goroutine 对其加锁,再利用其他 goroutine 对其解锁
  • 在同一个 goroutine 中的 Mutex 解锁之前再次进行加锁,会导致死锁
  • 适用于读写不确定,并且只有一个读或者写的场景

示例

加锁和解锁示例

package main

import (
    "time"
    "fmt"
    "sync"
)

func main() {
    var mutex sync.Mutex
    fmt.Println("Lock the lock")
    mutex.Lock()
    fmt.Println("The lock is locked")
    channels := make([]chan int, 4)
    for i := 0; i < 4; i++ {
        channels[i] = make(chan int)
        go func(i int, c chan int) {
            fmt.Println("Not lock: ", i)
            mutex.Lock()
            fmt.Println("Locked: ", i)
            time.Sleep(time.Second)
            fmt.Println("Unlock the lock: ", i)
            mutex.Unlock()
            c <- i
        }(i, channels[i])
    }
    time.Sleep(time.Second)
    fmt.Println("Unlock the lock")
    mutex.Unlock()
    time.Sleep(time.Second)

    for _, c := range channels {
        <-c
    }
}

程序输出:

Lock the lock
The lock is locked
Not lock:  1
Not lock:  2
Not lock:  0
Not lock:  3
Unlock the lock
Locked:  1
Unlock the lock:  1
Locked:  2
Unlock the lock:  2
Locked:  3
Unlock the lock:  3
Locked:  0
Unlock the lock:  0

在解锁之前加锁会导致死锁

package main

import (
    "fmt"
    "sync"
)

func main(){
    var mutex sync.Mutex
    mutex.Lock()
    fmt.Println("Locked")
    mutex.Lock()
}

程序输出:

Locked
fatal error: all goroutines are asleep - deadlock!

RWMutex(读写锁)

  • RWMutex 是单写多读锁,该锁可以加多个读锁或者一个写锁
  • 读锁占用的情况下会阻止写,不会阻止读,多个 goroutine 可以同时获取读锁
  • 写锁会阻止其他 goroutine(无论读和写)进来,整个锁由该 goroutine 独占
  • 适用于读多写少的场景

Lock() 和 Unlock()

  • Lock() 加写锁,Unlock() 解写锁
  • 如果在加写锁之前已经有其他的读锁和写锁,则 Lock() 会阻塞直到该锁可用,为确保该锁可用,已经阻塞的 Lock() 调用会从获得的锁中排除新的读取器,即写锁权限高于读锁,有写锁时优先进行写锁定
  • 在 Lock() 之前使用 Unlock() 会导致 panic 异常

RLock() 和 RUnlock()

  • RLock() 加读锁,RUnlock() 解读锁
  • RLock() 加读锁时,如果存在写锁,则无法加读锁;当只有读锁或者没有锁时,可以加读锁,读锁可以加载多个
  • RUnlock() 解读锁,RUnlock() 撤销单词 RLock() 调用,对于其他同时存在的读锁则没有效果
  • 在没有读锁的情况下调用 RUnlock() 会导致 panic 错误
  • RUnlock() 的个数不得多余 RLock(),否则会导致 panic 错误

示例

Lock() 和 Unlock()

package main

import (
    "sync"
    "fmt"
    "time"
)

func main() {
    var mutex *sync.RWMutex
    mutex = new(sync.RWMutex)
    fmt.Println("Lock the lock")
    mutex.Lock()
    fmt.Println("The lock is locked")

    channels := make([]chan int, 4)
    for i := 0; i < 4; i++ {
        channels[i] = make(chan int)
        go func(i int, c chan int) {
            fmt.Println("Not lock: ", i)
            mutex.Lock()
            fmt.Println("Locked: ", i)
            fmt.Println("Unlock the lock: ", i)
            mutex.Unlock()
            c <- i
        }(i, channels[i])
    }
    time.Sleep(time.Second)
    fmt.Println("Unlock the lock")
    mutex.Unlock()
    time.Sleep(time.Second)

    for _, c := range channels {
        <-c
    }
}

程序输出:

Lock the lock
The lock is locked
Not lock:  0
Not lock:  1
Not lock:  2
Not lock:  3
Unlock the lock
Locked:  0
Unlock the lock:  0
Locked:  2
Unlock the lock:  2
Locked:  3
Unlock the lock:  3
Locked:  1
Unlock the lock:  1

Lock() 和 RLock()

package main

import (
    "sync"
    "fmt"
    "time"
)

func main() {
    var mutex *sync.RWMutex
    mutex = new(sync.RWMutex)
    fmt.Println("Lock the lock")
    mutex.Lock()
    fmt.Println("The lock is locked")

    channels := make([]chan int, 4)
    for i := 0; i < 4; i++ {
        channels[i] = make(chan int)
        go func(i int, c chan int) {
            fmt.Println("Not read lock: ", i)
            mutex.RLock()
            fmt.Println("Read Locked: ", i)
            fmt.Println("Unlock the read lock: ", i)
            time.Sleep(time.Second)
            mutex.RUnlock()
            c <- i
        }(i, channels[i])
    }
    time.Sleep(time.Second)
    fmt.Println("Unlock the lock")
    mutex.Unlock()
    time.Sleep(time.Second)

    for _, c := range channels {
        <-c
    }
}

程序输出:

Lock the lock
The lock is locked
Not read lock:  2
Not read lock:  3
Not read lock:  1
Not read lock:  0
Unlock the lock
Read Locked:  2
Read Locked:  1
Unlock the read lock:  2
Unlock the read lock:  1
Read Locked:  0
Read Locked:  3
Unlock the read lock:  0
Unlock the read lock:  3

Unlock() 使用之前不存在 Lock()

package main

import (
    "sync"
)

func main(){
    var rwmutex *sync.RWMutex
    rwmutex = new(sync.RWMutex)
    rwmutex.Unlock()
}

程序输出:

panic: sync: Unlock of unlocked RWMutex

RWMutex 使用不当导致的死锁

示例1:

package main

import (
    "sync"
)

func main(){
    var rwmutex *sync.RWMutex
    rwmutex = new(sync.RWMutex)
    rwmutex.Lock()
    rwmutex.Lock()
}

程序输出:

fatal error: all goroutines are asleep - deadlock!

示例2:

package main

import (
    "sync"
)

func main(){
    var rwmutex *sync.RWMutex
    rwmutex = new(sync.RWMutex)
    rwmutex.Lock()
    rwmutex.RLock()
}

程序输出:

fatal error: all goroutines are asleep - deadlock!

RUnlock() 之前不存在 RLock()

package main

import (
    "sync"
)

func main(){
    var rwmutex *sync.RWMutex
    rwmutex = new(sync.RWMutex)
    rwmutex.RUnlock()
}

程序输出:

panic: sync: RUnlock of unlocked RWMutex

RUnlock() 个数多于 RLock()

package main

import (
    "sync"
)

func main(){
    var rwmutex *sync.RWMutex
    rwmutex = new(sync.RWMutex)
    rwmutex.RLock()
    rwmutex.RLock()
    rwmutex.RUnlock()
    rwmutex.RUnlock()
    rwmutex.RUnlock()
}

程序输出:

panic: sync: RUnlock of unlocked RWMutex

原文地址:https://www.cnblogs.com/ExMan/p/12396766.html

时间: 2024-11-10 13:41:50

golang 中 sync.Mutex 和 sync.RWMutex的相关文章

golang中的Mutex和RWMutex

????sync中有两种锁 Mutex和RWMutex,Mutex的读和写必须都进行排队,只能一个完成了在进行下一个,RWMutex读可以并行,写只能一个一个进行,当有读时,需要所有的读全部关闭后才能进行写操作,有写 时,需要等写操作完成了才能进行读操作(读并行,写单一).(sync中有一个map对象是线程安全的,默认的map不是线程安全的). Mutex 先看下面的代码: package main import ( "fmt" "sync" "time&

golang中锁mutex的实现

golang中的锁是通过CAS原子操作实现的,Mutex结构如下: type Mutex struct { state int32 sema  uint32 } //state表示锁当前状态,每个位都有意义,零值表示未上锁 //sema用做信号量,通过PV操作从等待队列中阻塞/唤醒goroutine,等待锁的goroutine会挂到等待队列中,并且陷入睡眠不被调度,unlock锁时才唤醒.具体在sync/mutex.go Lock函数实现中. 插播一下sema 虽然在Mutex中就是一个整形字段

golang sync.Mutex(2)

package main import ( "fmt" "sync" "time" ) type User struct { Name string Locker *sync.Mutex } func (u *User) SetName(wati *sync.WaitGroup, name string) { defer func() { fmt.Println("Unlock set name:", name) u.Lock

不得不知道的golang之sync.Mutex互斥锁源码分析

针对Golang 1.9的sync.Mutex进行分析,与Golang 1.10基本一样除了将panic改为了throw之外其他的都一样.源代码位置:sync\mutex.go.可以看到注释如下: Mutex can be in 2 modes of operations: normal and starvation. In normal mode waiters are queued in FIFO order, but a woken up waiter does not own the m

golang中sync和channel同步机制

sync实例: package main import ( "fmt" "sync") var waitgroup sync.WaitGroup func Afunction(shownum int) { fmt.Println(shownum) waitgroup.Done() //任务完成,将任务队列中的任务数量-1,其实.Done就是.Add(-1)} func main() { for i := 0; i < 10; i++ { waitgroup.A

golang sync.Mutex

//go func 和主线程之间的关系是并行和竞争关系 package main import ( "fmt" "sync" "time" ) var l sync.Mutex var m *sync.Mutex func main() { m = new(sync.Mutex) go lock(1) time.Sleep(3 * time.Second) fmt.Printf("%s\n", "exit!"

sync.Mutex (对map加锁)

A Tour of Go concurrency >> sync.Mutex https://tour.golang.org/concurrency/9 golang 里的 map 并不是 concurrency-safe 的,也就是说,当多个 goroutine 对同一个 map 进行操作时,有可能发生冲突. 教程中给出了一个例子,对 map 加锁避免冲突: 其中,如果把 go c.Inc("somekey") 改成 go func() { c.v["somek

在Golang中实现有无限容量的同步Queue

chan对象是Golang的一个核心卖点,可以轻松实现goroutine之间的通信.Golang允许我们为chan设置不同的缓冲大小.当默认缓冲大小为0的时候,一个goroutine对chan的写入操作必须要等到有其他goroutine对chan进行读取的时候才会返回,反之一个goroutine对chan进行读取的时候要等到另外一个goroutine对chan进行写入才会返回.如果我们不希望每次对chan进行读取和写入都堵塞的话,可以对chan设置缓冲大小.这样,在缓冲区没满之前,gorouti

Golang中使用heap编写一个简单高效的定时器模块

定时器模块在服务端开发中非常重要,一个高性能的定时器模块能够大幅度提升引擎的运行效率.使用Golang和heap实现一个通用的定时器模块,代码来自:https://github.com/xiaonanln/goTimer 也可以查看文档:http://godoc.org/github.com/xiaonanln/goTimer,下面是完整的代码,并进行适当的注释和分析. 从性能测试结果来看,基于heap的定时器模块在效率上并不会比时间轮(TimeWheel)的实现慢多少,但是逻辑上要简单很多.