互斥锁和读写锁
我们总是在 defer 语句中调用 Unlock 。这是一个十分常见的习惯用怯,它使用 Mutex 互斥锁来确保即使出现了 panic ,调用也总是发生。如果不这样,可能会导致程序陷入死锁。
Cond
package mainimport ("fmt""sync""time")func main() {c := sync.NewCond(&sync.Mutex{})queue := make([]interface{}, 0, 10)removeFromQueue := func(delay time.Duration) {time.Sleep(delay)c.L.Lock()queue = queue[1:]fmt.Println("Removed from queue")c.L.Unlock()c.Signal() // 关键}for i := 0; i < 10; i++ {c.L.Lock()for len(queue) == 2 {c.Wait() // 关键}fmt.Println("Adding to queue")queue = append(queue, struct{}{})go removeFromQueue(1 * time.Second)c.L.Unlock()}}
Once
package mainimport ("fmt""sync")func main() {var count intincrement := func() {count++}var once sync.Oncevar increments sync.WaitGroupincrements.Add(100)for i := 0; i < 100; i++ {go func() {defer increments.Done()once.Do(increment)}()}increments.Wait()fmt.Printf("Count is %d\n", count)}输出:Count is 1
package mainimport ("fmt""sync")func main() {var count intincrement := func() { count++ }decrement := func() { count-- }var once sync.Onceonce.Do(increment)once.Do(decrement)fmt.Printf("Count: %d\n", count)}输出:Count: 1
注意 sync.Once 只计算调用 Do 方法的次数,而不是多少次唯一调用 Do 方法。
package mainimport ("sync")func main() {var onceA, onceB sync.Oncevar initB func()initA := func() {onceB.Do(initB)}initB = func() {onceA.Do(initA)}onceA.Do(initA)}输出:fatal error: all goruntines are asleep - deadlock
Pool
package mainimport ("fmt""sync")func main() {myPool := &sync.Pool{New: func() interface{} {fmt.Println("Creating new instance")return struct{}{}}}a := myPool.Get()fmt.Println("a:", a)instance := myPool.Get()fmt.Println("instacne:", instance)myPool.Put(instance)c := myPool.Get()fmt.Println("c:", c)}输出:Creating new instancea: {}Creating new instanceinstacne: {}c: {}


package mainimport ("fmt""sync")func main() {var numCalcsCreated intcalcPool := &sync.Pool{New: func() interface{} {numCalcsCreated += 1mem := make([]byte, 1024)return &mem},}calcPool.Put(calcPool.New())calcPool.Put(calcPool.New())calcPool.Put(calcPool.New())calcPool.Put(calcPool.New())const numWorkers = 1024 * 1024var wg sync.WaitGroupwg.Add(numCalcsCreated)for i := 0; i < numCalcsCreated; i++ {go func() {defer wg.Done()mem := calcPool.Get().(*[]byte)defer calcPool.Put(mem)}()}wg.Wait()fmt.Printf("%d calculators were created.", numCalcsCreated)}输出:4 calculators were created.
