代码演示:
package main import ( "fmt" "math/rand" "runtime" "sync" "sync/atomic" "time" ) func main() { var state = make(map[int]int) var mutex = &sync.Mutex{} var ops int64 = 0 for r := 0; r < 100; r++ { go func() { total := 0 for { key := rand.Intn(5) + 1 mutex.Lock() total += state[key] mutex.Unlock() atomic.AddInt64(&ops, 1) runtime.Gosched() } }() } for w := 0; w < 10; w++ { go func() { for { key := rand.Intn(5) + 1 val := rand.Intn(100) + 1 mutex.Lock() state[key] = val mutex.Unlock() atomic.AddInt64(&ops, 1) runtime.Gosched() } }() } time.Sleep(time.Second) opsFinal := atomic.LoadInt64(&ops) fmt.Println("ops:", opsFinal) mutex.Lock() fmt.Println("state:", state) mutex.Unlock() }
代码运行结果:
ops: 4728620 state: map[5:4 2:90 4:16 3:84 1:77]
代码解读:
- 互斥锁用来使go协程间访问数据更加安全,当一个数据上锁之后,其它人就无法就该数据进行操作,一直到解锁后
- 以上例子中,我们对state这个map进行了读写操作,并在读写过程中运用互斥锁
- 本例中创建了一个读的函数和一个写的函数,均运用了互斥锁
- 最终打印state时候,也上了锁,这是因为,有可能协程还没有读写完state,上锁为了安全的输出结果
原文地址:https://www.cnblogs.com/Joestar/p/8870052.html
时间: 2024-10-09 09:30:52