Cond--Condition variable concurrency primitive

Let's not talk about what this cond is, let's start from a scene:

There is a charity organization that needs to raise money, and the goal is 1 million, for example. Then an announcement needs to be issued stating that 1 million donations need to be raised. The masses began to donate money when they saw the announcement. Everyone has different abilities. Some may be 10,000, some may be 20,000, and some people don't think it is enough to donate. In order to raise enough money faster, it must be that the more people the better, that in the computer world is to use all the CPU resources. Soon 1 million will be enough, and the charity will issue another announcement saying that the money is enough and everyone does not need to donate. Then there may be a delay in the delivery of this message. If the money received is more than 1 million, there is no way. You can count as much as you receive. As long as you can truthfully announce it and use it correctly.

To abstract the appeal scene, the process of donating money together and publicizing it after reaching 1 million can be realized with Cond

func main() {
    
    
	c := sync.NewCond(&sync.Mutex{
    
    })
	var ready int //善款总额,单位万
	ctx, cancle := context.WithCancel(context.Background())
	for i := 0; i < runtime.NumCPU(); i++ {
    
     //尽可能多的人捐款,即充分利用cpu资源
		go func(i int) {
    
    
			for {
    
    
				select {
    
    
				case <-ctx.Done():
					log.Printf("已经100万了,那我[%v号选手]就不捐了", i)
					return
					//已经看到公告够了100万了,那就不捐了
				default:
					//想一下要捐多少
					time.Sleep(time.Duration(rand.Int63n(5)) * time.Second)
					// 加锁更改等待条件
					c.L.Lock()
					ad := rand.Intn(5)
					if ad == 0 {
    
    
						//准备捐一个空头账户,那不行,重新捐
						c.L.Unlock()
						break
					}
					ready += ad
					c.L.Unlock()
					log.Printf("[%v号选手]捐了%v万", i,ad)
					// 让慈善机构核对一下到100万了没
					c.Broadcast()
				}
			}
		}(i)
	}
	c.L.Lock()
	for ready < 100 {
    
    
		c.Wait()
		log.Printf("现在%v万", ready)
	}
	c.L.Unlock()
	log.Println("善款已经够一百万了,不用再捐了")
	cancle()
}

This concurrency primitive is rarely used. You can know the usage scenarios and how to use it. For
in-depth understanding, please refer to: Cond: Conditional Variable Implementation Mechanism and Guide to Avoiding Pitfalls

Guess you like

Origin blog.csdn.net/csdniter/article/details/111043617