并发会产生的问题 -竞争
11.3.1 并发产生问题的代码
package main
import (
"fmt"
"sync"
)
var total int
var wg sync.WaitGroup
func add(){
defer wg.Done()
for i := 0; i < 100000; i ++ {
total += 1
}
}
func sub(){
defer wg.Done()
for i := 0; i < 100000; i ++ {
total -= 1
}
}
func main(){
wg.Add(2)
go add()
go sub()
wg.Wait()
fmt.Println(fmt.Sprintf("total is: %d", total))
}
11.3.2 通过互斥锁解决并发问题
package main
import (
"fmt"
"sync"
)
var total int
var wg sync.WaitGroup
var lock sync.Mutex
func add(){
defer wg.Done()
for i := 0; i < 100000; i ++ {
lock.Lock()
total += 1
lock.Unlock()
}
}
func sub(){
defer wg.Done()
for i := 0; i < 100000; i ++ {
lock.Lock()
total -= 1
lock.Unlock()
}
}
func main(){
wg.Add(2)
go add()
go sub()
wg.Wait()
fmt.Println(fmt.Sprintf("total is: %d", total))
}
11.3.3 读写锁
package main
import (
"fmt"
"sync"
"time"
)
var rwLock sync.RWMutex
var wg sync.WaitGroup
func read(){
defer wg.Done()
rwLock.RLock()
fmt.Println("读取数据")
time.Sleep(time.Second)
fmt.Println("读取成功")
rwLock.RUnlock()
}
func write(){
defer wg.Done()
rwLock.Lock()
fmt.Println("修改数据")
time.Sleep(time.Second*10)
fmt.Println("修改成功")
rwLock.Unlock()
}
func main() {
wg.Add(10)
for i := 0;i<5;i++ {
go read()
}
for i := 0;i<5;i++ {
go write()
}
wg.Wait()
}