• Go语言协程并发---条件变量案例《城管来啦》


    package main
    
    import (
    	"fmt"
    	"sync"
    	"time"
    )
    
    /*
    城管预警
    ·监听城管大队
    ·烧烤摊集群:监听城管大队,只要出动就发消息通知工会主席并进入阻塞等待至被唤醒,否则就提供露天烧烤
    ·公关专员:摆平城管大队,并广播通知所有烧烤摊主
    */
    
    func main() {
    	var dangerous = false
    	cond := sync.NewCond(&sync.Mutex{})
    	chDanger := make(chan string, 1)
    
    	for i := 1; i <= 3; i++ {
    		go func(index int) {
    			for true {
    				//只要城管出来,就等待起来
    				cond.L.Lock()
    				for dangerous==true{
    					//发送预警
    					select {
    					case chDanger <- "城管来了!!":
    						fmt.Println("城管来了!")
    						fmt.Println(index,":蛰伏状态")
    					default:
    						//已经有人发过了
    					}
    
    					cond.Wait()
    				}
    				cond.L.Unlock()
    
    
    				//城管没出来
    				fmt.Println(index,":提供露天烧烤")
    				time.Sleep(3*time.Second)
    			}
    
    		}(i)
    	}
    
    	go func() {
    		for true {
    			select {
    			case <-chDanger:
    				//帮大家平事儿
    				cond.L.Lock()
    				time.Sleep(3*time.Second)
    				dangerous=false
    				fmt.Println("事情已经摆平")
    				cond.Broadcast()
    				cond.L.Unlock()
    			default:
    				//日常生活
    				fmt.Println("工会主席的日常幸福生活")
    				dangerous=true
    				time.Sleep(3*time.Second)
    			}
    		}
    	}()
    
    	time.Sleep(365*time.Second)
    }
    

      

  • 相关阅读:
    【leetcode】206. 反转链表
    【leetcode】25. K 个一组翻转链表
    【leetcode】160. 相交链表
    【leetcode】92. 反转链表 II
    C# Socket通信
    正则表达式的学习
    python操作数据库sqlite3
    python爬取淘宝商品信息
    《Unix/Linux系统编程》第七、八章学习笔记 20201209戴骏
    ls的实现
  • 原文地址:https://www.cnblogs.com/yunweiqiang/p/12776505.html
Copyright © 2020-2023  润新知