面向奶酪:用同步与互斥锁,讲“美食争夺”。

faceNL · · 1002 次点击
buguang01
https://github.com/buguang01
func main() { mutex := sync.Mutex{} wg := new(sync.WaitGroup) wg2 := new(sync.WaitGroup) food := []string{"西瓜", "巧克力", "蛋糕", "土司", "饼干"} wg.Add(1) wg2.Add(3) go func() { //协程a wg.Wait() mutex.Lock() food[0] = "哈密瓜" fmt.Println("协程A:我把西瓜换成了哈密瓜", food) mutex.Unlock() wg2.Done() }() go func() { //协程b wg.Wait() mutex.Lock() food[0] = "火龙果" fmt.Println("协程B:我把西瓜换成了火龙果", food) mutex.Unlock() wg2.Done() }() go func() { //协程c wg.Wait() mutex.Lock() food[0] = "榴莲" fmt.Println("协程C:我把西瓜换成了榴莲", food) mutex.Unlock() wg2.Done() }() wg.Done() wg2.Wait() }
#3
更多评论
buguang01
https://github.com/buguang01
1、第一个例子中每往Chan写一个数据,就有二个GO从里面读数据,导致你最后在关闭时,还有一半的GO没正常关闭。正常的程序不应该这样写,导致GO泄漏 2、由于你的例子中是顺序开启这些GO,所以他们的顺序是确定的。虽然,实际中有可能会发生竞争,但是可能性比较小。 建议修改如下
#1
buguang01
https://github.com/buguang01
func main() { const err = false ch := make(chan string, 2) //加个缓存,防止阻塞 var food = []string{"饼干", "可乐", "夹心饼", "奶酪", "雪碧", "火龙果", "冰镇西瓜", "火鸡面", "土司", "冰淇淋"} go func(ch <-chan string) { for c := range ch { fmt.Println("Mr.Cheese 抢到了 ", c) } }(ch) go func(ch <-chan string) { for c := range ch { fmt.Println("Mr.Potato 抢到了 ", c) } }(ch) for _, v := range food { ch <- v } close(ch) time.Sleep(1* time.Second) // 等待1秒!!! }
#2