python Thread Condition

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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值