您好,登錄后才能下訂單哦!
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()
思路:需要有 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("主線程完成")
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。