go练习- 读写锁和互斥锁

package main

import (
	"fmt"
	"sync"
	"time"

)

//读写互斥锁

var (
	x  int64
	wg sync.WaitGroup
	//互斥锁
	lock sync.Mutex
	rwLock sync.RWMutex
)

func read() {
	//互斥锁
	//lock.Lock()
	//读锁
	rwLock.RLock()
	time.Sleep(time.Millisecond)
	//解互斥锁
	//lock.Unlock()
	//解读锁
	rwLock.RUnlock()
	wg.Done()
}

func write() {
	//加互斥锁
	//lock.Lock()
	//加写锁
	rwLock.Lock()
	x = x +1
	time.Sleep(time.Millisecond * 10)
	//解互斥锁
	//lock.Unlock()
	//接写锁
	rwLock.Unlock()
	wg.Done()
}
func main() {
	start := time.Now()

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go read()
	}
	for i:=0;i<10;i++ {
		wg.Add(1)
		go write()
	}
	//等待程序执行完毕
	wg.Wait()
	fmt.Println(time.Now().Sub(start))
}

循环
请先登录后发表评论
  • latest comments
  • 总共0条评论