Python: threading.Event

 

 

生产杯子

import time, logging, threading

FORMAT = '%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)


def boss(event: threading.Event):
    logging.critical(f'boss waiting {event.is_set()}')
    event.wait()
    logging.info(f'boss done {event.is_set()}')


def worker(event: threading.Event, n=10):
    logging.info(f'worker working')
    cups = []
    while True:
        time.sleep(0.2)
        cups.append(1)
        logging.info(f'produce {len(cups)} cup')
        if len(cups) >= n:
            event.set()
            break
    logging.info(f'finished {len(cups)} cups')


event = threading.Event()
b = threading.Thread(name='boss', target=boss, args=(event,))
w = threading.Thread(name='worker', target=worker, args=(event, 10))

b.start()
w.start()

b.join()
w.join()

logging.error(f'outer finished')

 

 

import time, logging, threading

FORMAT = '%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)


def do(event: threading.Event, timeout: int):
    while not event.wait(timeout=timeout):
        logging.info('timeout')


event = threading.Event()
threading.Thread(target=do, args=(event, 2)).start()
event.wait(10)  # 可换成time.sleep(10)
event.set()
print('main exit')

1

 

 

 

 

 

import time, logging, threading, datetime

FORMAT = '%(asctime)s %(threadName)s %(thread)d %(message)s'
logging.basicConfig(level=logging.INFO, format=FORMAT)


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


class Timer:
    def __init__(self, interval, function, *args, **kwargs):
        self.interval = interval
        self.function = function
        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(f'self = {self} waiting')
        self.event.wait(timeout=self.interval)

        if not self.event.is_set():
            self.function(*self.args, **self.kwargs)
        delta = (datetime.datetime.now() - start)
        logging.critical(f'elapsed {delta}')


t = Timer(3, vagary, 5, 55)
t.start()
threading.Event().wait(1)
t.cancel()

 

posted @ 2022-02-24 22:02  ascertain  阅读(89)  评论(0编辑  收藏  举报