DAY 25
1
Software Development

# Mutex 互斥鎖

## sync.Mutex 使用

``````type Mutex struct {
state int32
sema  uint32
}

func (m *Mutex) Lock()

func (m *Mutex) Unlock()
``````

sync.Mutex的零值表示未被鎖定的互斥量。

## 舉例

``````package main

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

var m *sync.Mutex

func main() {
m = new(sync.Mutex)
time.Sleep(time.Second) // 让goroutine有足够的时间执行完
}

fmt.Println(i, "begin lock")
m.Lock()
fmt.Println(i, "in lock")
m.Unlock()
fmt.Println(i, "unlock")
}
``````

``````1 begin lock // goroutine1 獲得互斥鎖
2 begin lock // goroutine2 未獲得互斥鎖，因此被堵塞
1 in lock
1 unlock
2 in lock    // 互斥鎖釋放後，喚醒 goroutine2
2 unlock
``````

# RWMutex 讀寫鎖

## 使用

``````type RWMutex struct {
w           Mutex  // held if there are pending writers
writerSem   uint32 // semaphore for writers to wait for completing readers
}

func (*RWMutex) Lock    // 寫鎖

func (*RWMutex) Unlock

func (*RWMutex) RLock   // 讀鎖

func (*RWMutex) RUnlock

``````

## 範例

``````package main

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

var m *sync.RWMutex
var val = 0

func main() {
m = new(sync.RWMutex)
go write(2)
time.Sleep(5 * time.Second)
}

m.RLock()
time.Sleep(1 * time.Second)
fmt.Println(i, "val: ", val)
time.Sleep(1 * time.Second)
m.RUnlock()
}

func write(i int) {
fmt.Println(i, "begin write")
m.Lock()
val = 10
fmt.Println(i, "val: ", val)
time.Sleep(1 * time.Second)
m.Unlock()
fmt.Println(i, "end write")
}
``````

# sync.Once 唯一鎖

## 使用

``````type Once struct {
m    Mutex
done uint32
}

func (o *Once) Do(f func())
``````

## 範例

``````package main

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

func main() {
var once sync.Once
for i := 0; i < 10; i++ {
go func() {
}()
}
time.Sleep(time.Second)
}