Condition.accquire() 和while True
代码说明:老师有一份名单,持续点到,学生陆续进入,如果被点到则回答到,然后从名单中去掉,直到所有人都到了。
import threading
from queue import Queue
from threading import Thread
import time
class Stu(Thread):
global count
def __init__(self, name2):
super().__init__()
self.name = name2
print("~~~~~~~~~~~~~~~~{}到教室了~".format(self.name))
def run(self):
global count
global name
global name_list
while True:
with cond:
# 阻塞程序,时刻监听老师,接收消息
# 一旦发现点到自己名字,就赶紧答到
if str(name) == str(self.name):
print("{}:到!".format(name))
# print("{} ".format(threading.current_thread()))
name_list.remove(name)
count += 1
name = 0
break
else:
cond.wait()
class Tea(Thread):
def __init__(self, name3):
super(Tea, self).__init__()
self.name = name3
self.stu_num = len(name_list)
def run(self):
global name_list
global name
# with cond:
while True:
if count == self.stu_num:
print("{} all here".format(count))
break
sub_name_list = name_list.copy()
for name1 in sub_name_list:
time.sleep(1)
with cond:
print("老师:{}来了没?".format(name1))
name = name1
cond.notify_all()
cond.wait(timeout=0.3)
class Consumer(threading.Thread):
def run(self):
pass
def main():
t1 = Tea("teacher1")
t1.start()
ll = [14, 3, 1, 2, 10, 7, 9, 6, 12, 13, 8, 4, 11, 5]
# random.shuffle(ll)
for ii in ll:
time.sleep(1)
s = Stu(ii)
s.start()
if __name__ == '__main__':
main()