go 传统同步机制-mutex

mac2026-09-02  7

package main import ( "fmt" "sync" "time" ) /*传统的同步机制很少使用到,因为传统的同步机制都是用共享内存来交换数据的,所以才需要mutxt cond去保护*/ type atomicInt struct { value int lock sync.Mutex //锁 } /*atomic 在多个goroutine之间是安全的*/ //互斥量 func (a *atomicInt) increment(){ a.lock.Lock() //锁住数据 defer a.lock.Unlock()//做完之后解锁数据 a.value ++ } //将锁控制在一段代码区域中 func (a *atomicInt) incremenSafeSpace(){ fmt.Println("safe space:start") func(){ a.lock.Lock() //锁住数据 defer a.lock.Unlock()//做完之后解锁数据 a.value ++ }() fmt.Println("safe space:end") } func (a *atomicInt) get() int { a.lock.Lock() defer a.lock.Unlock() return a.value } func main() { var a atomicInt a.increment() go func() { //写 a.incremenSafeSpace() }() time.Sleep(time.Second) //读 // fmt.Println(a.get()) /* 在读的时候写,发生了冲突 go run -race atomic.go ================== WARNING: DATA RACE Read at 0x00c000096008 by main goroutine: main.main() /Users/tao/go/src/learn/basic/channel10/atomic/atomic.go:31 +0xc5 Previous write at 0x00c000096008 by goroutine 7: main.main.func1() /Users/tao/go/src/learn/basic/channel10/atomic/atomic.go:14 +0x51 Goroutine 7 (finished) created at: main.main() /Users/tao/go/src/learn/basic/channel10/atomic/atomic.go:24 +0xaa ================== */ }

 

最新回复(0)