如何启动和停止线程? [英] How to start and stop thread?
本文介绍了如何启动和停止线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉这个老问题.我已经澄清了.我该如何使用不良的线程类启动停止线程?
Sorry for the old question. I have clarified it. How can I start an stop thread with my poor thread class?
EDIT :它正在循环中,我想在代码开头再次重新启动它.我该如何开始-停止-重新启动-停止-重新启动?
EDIT: It is in loop, I want to restart it again at the beginning of the code. How can I do start-stop-restart-stop-restart?
我的课:
import threading
class Concur(threading.Thread):
def __init__(self):
self.stopped = False
threading.Thread.__init__(self)
def run(self):
i = 0
while not self.stopped:
time.sleep(1)
i = i + 1
在主代码中,我想要:
inst = Concur()
while conditon:
inst.start()
#after some operation
inst.stop()
#some other operation
推荐答案
这是David Heffernan的构想.下面的示例运行1秒钟,然后停止1秒钟,然后运行1秒钟,依此类推.
This is David Heffernan's idea fleshed-out. The example below runs for 1 second, then stops for 1 second, then runs for 1 second, and so on.
import time
import threading
import datetime as DT
import logging
logger = logging.getLogger(__name__)
def worker(cond):
i = 0
while True:
with cond:
cond.wait()
logger.info(i)
time.sleep(0.01)
i += 1
logging.basicConfig(level=logging.DEBUG,
format='[%(asctime)s %(threadName)s] %(message)s',
datefmt='%H:%M:%S')
cond = threading.Condition()
t = threading.Thread(target=worker, args=(cond, ))
t.daemon = True
t.start()
start = DT.datetime.now()
while True:
now = DT.datetime.now()
if (now-start).total_seconds() > 60: break
if now.second % 2:
with cond:
cond.notify()
这篇关于如何启动和停止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文