包含了sync.Mutex,sync.RWMutex,sync.Cond,sync.Map,sync.Once等demo
sync.Mutex
//讲解mutex
import (
"fmt"
"math/rand"
"sync"
"time"
)
type Toilet struct {
m sync.Mutex
}
type Person struct {
Name string
}
var DateTime = "2006-01-02 15:04:05"
var otherThing = []string{
"唱歌", "跳舞", "修仙"}
func main() {
t := &Toilet{
}
wg := sync.WaitGroup{
}
wg.Add(5)
for i := 0; i < 5; i++ {
go func(i int, t *Toilet, wg *sync.WaitGroup) {
p := Person{
Name: fmt.Sprintf("%d 号", i),
}
p.InToiletLock(t, wg)
}(i, t, &wg)
}
wg.Wait()
}
func (p *Person) InToiletLock(t *Toilet, wg *sync.WaitGroup) {
defer wg.Done()
t.m.Lock()
i := rand.Intn(5)
fmt.Printf("%s 上厕所时间 %v\n", p.Name, time.Now().Format(DateTime))
time.Sleep(time.Duration(i) * time.Second)
t.m.Unlock()
}
func (p *Person) InToiletUnLock(wg *sync.WaitGroup) {
defer wg.Done()
i := rand.Intn(5)
fmt.Printf("%s 上厕所时间 %v\n", p.Name, time.Now().Format(DateTime))
time.Sleep(time.Duration(i) * time.Second)
}
sync.RWMutex
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
type Cinema struct {
rw *sync.RWMutex
}
type Person struct {
Name string
}
type Admin struct {
Name string
}
func main() {
//example01()
exmples2()
}
func (p *Person) SitDown(wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("%s 观众坐下!\n", p.Name)
}
func (p *Person) StartWatch() {
fmt.Printf("%s 开始观看!\n", p.Name)
i := time.Duration(rand.Intn(5) + 1)
time.Sleep(i * time.Second)
fmt.Printf("%s 观看结束!\n", p.Name)
}
func (p *Person) WatchMovie<