add: 锁的使用

This commit is contained in:
洪晓威 2022-02-13 14:13:10 +08:00
parent ea348b07a6
commit a8496afb35
2 changed files with 81 additions and 0 deletions

View File

@ -0,0 +1,34 @@
package main
import (
"fmt"
"sync"
"time"
)
type Sth struct {
x int64
wg sync.WaitGroup
lock sync.Mutex
}
func (s *Sth) add() {
for i := 0; i < 10000; i++ {
s.lock.Lock()
s.x++
s.lock.Unlock()
}
s.wg.Done()
}
func main() {
var s Sth
s.wg.Add(2)
go s.add()
go s.add()
s.wg.Wait()
fmt.Println(s)
time.Sleep(time.Second)
fmt.Println("xiaowei zhaodandan")
}

View File

@ -0,0 +1,47 @@
package main
import (
"fmt"
"sync"
"time"
)
var (
x int64
wg sync.WaitGroup
rwlock sync.RWMutex
lock sync.Mutex
)
func main() {
start := time.Now()
for i := 0; i < 10; i++ {
wg.Add(1)
go write()
}
for i := 0; i < 100; i++ {
wg.Add(1)
go read()
}
wg.Wait()
fmt.Println("cost:", time.Since(start))
}
func read() {
//lock.Lock()
rwlock.RLock()
time.Sleep(time.Millisecond)
//lock.Unlock()
rwlock.RUnlock()
wg.Done()
}
func write() {
rwlock.Lock()
//lock.Lock()
x = x + 1
time.Sleep(10 * time.Millisecond)
//lock.Unlock()
rwlock.Unlock()
wg.Done()
}