Python线程Event例子

发布时间:2020-07-12 00:04:18 作者:windcharger
来源:网络 阅读:575
需求1:Boss需要一个员工生产100个杯子,Boss一直等待员工生产完成之后方可
import threading
import logging
import time

logging.basicConfig(level=logging.INFO)

def worker(event:threading.Event, count=10):
    logging.info("I'm working for U.")
    cups = []
    while True:
        logging.info('make 1')
        time.sleep(0.5)
        cups.append(1)
        if len(cups) >= count:
            event.set()
            break
    logging.info('I finished my job. cups={}'.format(cups))

def boss(event:threading.Event):
    logging.info("I'm boss, waiting for U.")
    event.wait()
    logging.info("Good Job")

Event = threading.Event()
w = threading.Thread(target=worker, args=(Event, 100))
b = threading.Thread(target=boss, args=(Event, ))
w.start()
b.start()
需求2:使用threading Event实现类似Timer延迟执行的线程
思路:需要有 start和 cancel的功能(使用 Event  wait(),set(), 方法)
代码实现:
import threading
import datetime
import logging

logging.basicConfig(level=logging.INFO)

def add(x:int, y:int):
    logging.info(x + y)

class Timer(object):
    def __init__(self, interval, fn, *args, **kwargs):
        self.interval = interval
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.event = threading.Event()

    def start(self):
        threading.Thread(target=self.__run).start()

    def cancel(self):
        self.event.set()

    def __run(self):
        start = datetime.datetime.now()
        logging.info('Waiting')

        self.event.wait(self.interval)
        if not self.event.is_set():
        # 上面两行可以直接改写成 if not self.event.wait(self.interval):
            self.fn(*self.args, **self.kwargs)
        delta = (datetime.datetime.now() - start).total_seconds()
        logging.info('finished {}'.format(delta))
        self.event.set()

t = Timer(10, add, 4, 50)
t.start()
e = threading.Event()
e.wait(4)
t.cancel()

print("主线程完成")
推荐阅读:
  1. python线程事件Event的应用
  2. 40线程2_Event_Lock

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python event nt

上一篇:指针150206204

下一篇:比特币代码分析11 比特币存储机制

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》