add: 锁的使用
This commit is contained in:
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")
|
||||
}
|
||||
Reference in New Issue
Block a user