博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络编程 - 事件处理
阅读量:7048 次
发布时间:2019-06-28

本文共 1094 字,大约阅读时间需要 3 分钟。

一、事件主要包括3种:

1、event.set() #设置标志位;

2、event.clear() #清除标志位;

3、event.wait() #未设置标志位时,等待;

4、以下例子,实现红绿灯及车的线程关系(当红灯时,车等待,当绿灯时,车通行)

     通过对红绿灯线程设置事件的标志位,当设置标志位时,代表车辆通行。当标志位清除时,代表红灯,代表车辆等待。当再次设置标志位时,车辆等待清除,视为绿灯)。

 

import threading,time event = threading.Event() def lighter():     event.set()     count = 1     while True:         if count<=6 and count>3:#清除标志位,代表红灯;             event.clear()             print("\033[41;1mred light is on...\033[0m")         elif count>6 :#设置标志位,代表绿灯;             event.set()             count=0         else:#标志们,初始值;             print ("\033[42;1mgreen light is on...\033[0m")         time.sleep(1)         count+=1 def car(name):     while True:         if event.is_set():             print ("[%s] is running..." % name)             time.sleep(1)         else:             print ("[%s] sees  red light...waiting..." % name)             event.wait()             print ("green light is on ,going....") light = threading.Thread(target=lighter) light.start() car = threading.Thread(target=car,args=("tesla",)) car.start()

转载于:https://www.cnblogs.com/wulafuer/p/10240056.html

你可能感兴趣的文章
Linux系统简介--LInix系统随笔(一)
查看>>
TCP接入层的负载均衡、高可用、扩展性架构
查看>>
使用Kieker(AspectJ)监控控制台程序
查看>>
C#多线程之旅(1)——介绍和基本概念
查看>>
Spring常用注解汇总
查看>>
10大最重要的Web安全风险之六--A6-安全误配置
查看>>
Hibernate【与Spring整合】
查看>>
NOIP2018 游记
查看>>
Redis 和 Memcached 的区别
查看>>
关于tcp状态及一些延展
查看>>
JS入门
查看>>
.vimrc
查看>>
内容显示在HTML页面底端的一些处理方式
查看>>
字符编码总结
查看>>
Vue 2.0 Application Sample
查看>>
小程序 wx:for 循环嵌套
查看>>
IE, FireFox, Opera 浏览器支持CSS实现Alpha半透明的方法
查看>>
wpf中插入winform控件并获取句柄
查看>>
Windows 8 Metro App开发[3]应用程序栏(AppBar)的使用
查看>>
bootstrap 智能表单 demo示例
查看>>