// Values containing the types defined in this package should not be copied.
// A Mutex must not be copied after first use.
sync/rwmutex.go
1
// A RWMutex must not be copied after first use.
sync/cond.go
1
// A Cond must not be copied after first use.
sync/mutex.go
1 2 3 4 5 6 7 8
// A Mutex is a mutual exclusion lock. // The zero value for a Mutex is an unlocked mutex. // // A Mutex must not be copied after first use. type Mutex struct { state int32// 表示当前互斥锁的状态 sema uint32// 用于控制锁状态的信号量 }
funcworker(i int) { fmt.Printf("worker %d: is working\n", i) time.Sleep(time.Second) fmt.Printf("worker %d: is done\n", i) }
funcspawnGroup(f func(i int), num int, mu *sync.Mutex) <-chan signal { c := make(chan signal) var wg sync.WaitGroup
for i := 0; i < num; i++ { wg.Add(1) gofunc(i int) { defer wg.Done()
for { mu.Lock() if !ready { mu.Unlock() time.Sleep(time.Millisecond * 100) continue } mu.Unlock() fmt.Printf("worker %d: start to work\n", i) f(i) break } }(i) }
gofunc() { wg.Wait() c <- signal{} }()
return c }
funcmain() { fmt.Println("start a group of workers") mu := &sync.Mutex{} c := spawnGroup(worker, 10, mu)
time.Sleep(time.Second * 5) fmt.Println("ready to work")
gofunc() { mu.Lock() ready = true mu.Unlock() }()
<-c fmt.Println("all workers are done") }
// Output: // start a group of workers // ready to work // worker 6: start to work // worker 6: is working // worker 0: start to work // worker 0: is working // worker 2: start to work // worker 2: is working // worker 9: start to work // worker 9: is working // worker 8: start to work // worker 8: is working // worker 1: start to work // worker 1: is working // worker 3: start to work // worker 3: is working // worker 4: start to work // worker 4: is working // worker 7: start to work // worker 7: is working // worker 5: start to work // worker 5: is working // worker 1: is done // worker 6: is done // worker 0: is done // worker 2: is done // worker 9: is done // worker 8: is done // worker 5: is done // worker 3: is done // worker 4: is done // worker 7: is done // all workers are done
// Output: // start a group of workers // ready to work // worker 6: start to work // worker 6: is working // worker 0: start to work // worker 0: is working // worker 2: start to work // worker 2: is working // worker 9: start to work // worker 9: is working // worker 8: start to work // worker 8: is working // worker 1: start to work // worker 1: is working // worker 3: start to work // worker 3: is working // worker 4: start to work // worker 4: is working // worker 7: start to work // worker 7: is working // worker 5: start to work // worker 5: is working // worker 1: is done // worker 6: is done // worker 0: is done // worker 2: is done // worker 9: is done // worker 8: is done // worker 5: is done // worker 3: is done // worker 4: is done // worker 7: is done // all workers are done