标签:thread lease inpu random for reading import range false
# 模拟拿数据断网了的操作
from threading import Thread, Event
import random
import time
e = Event()
def foo():
while 1:
e.wait(3) # 阻塞,如果时间状态为False则会阻塞,反之,可以通过
time.sleep(0.6)
if e.is_set() == True: # is_set 查看事件状态为False还是True
print("拿到数据啦")
else:
print("断网了")
break
def foo1():
for i in range(5):
time.sleep(1)
state = i
if state != 3:
e.set() # 如果不为3,就把他设置成True,就可以取数据
else:
e.clear() # 如果为3,就设置成False
def foo2():
time.sleep(4)
e.set()
t = Thread(target=foo)
t1 = Thread(target=foo2)
t.start()
t1.start()
# 条件其实就是更加复杂的锁
from threading import Thread,Condition
cond = Condition()
def foo():
cond.acquire() # 必须包裹住 wait() 方法
cond.wait()
print("进来一个")
cond.release() # 必须包裹住 wait() 方法
for i in range(10): # 设置10个线程,通过完就没有了
t = Thread(target=foo)
t.start()
while 1:
num = input("请输入放行的子进程个数:") # 相当于给线程设置了个告诉加油站的收费处
cond.acquire() # 必须包裹住 notify() 方法
cond.notify(int(num))
cond.release() # 必须包裹住 notify() 方法
标签:thread lease inpu random for reading import range false
原文地址:https://www.cnblogs.com/xiongchao0823/p/11552405.html