add: 锁的使用
This commit is contained in:
parent
ea348b07a6
commit
a8496afb35
34
channel/mutex/basic/main.go
Normal file
34
channel/mutex/basic/main.go
Normal 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")
|
||||||
|
}
|
47
channel/mutex/rwlock/main.go
Normal file
47
channel/mutex/rwlock/main.go
Normal 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()
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user