我想在python3中创建一个线程类。我想在其中一个类函数中控制一个无限循环。我想在课外的主函数中启动或停止这个循环。假设这段代码:
import threading
from time import sleep
class my_thread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self):
super(my_thread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
print("stopping the thread")
self._stop_event.set()
def stopped(self):
return(self._stop_event.is_set())
def run(self):
print("running the thread")
print("start function startt()")
self._stop_event.clear()
self.startt()
def startt(self):
print("it is going to wait forever")
while not self.stopped():
#wait forever, this part is going to run again and again
pass
print("This line never executes")
if __name__+'__main__':
thr=my_thread()
thr.start()
sleep(5)
print("stopping the thread")
thr.stop()
# I cant start the thread and relative while loop again
#thr.start()
print("Exiting the whole program")
但问题是我无法启动线程两次,所以我想要的是有两个函数用于启动和停止我的while循环。我不需要停止线程,但我需要控制它。这意味着我想在主程序中需要多次调用stop()
和startt()
函数。
感谢
答案 0 :(得分:1)
首先,在my_thread类中使用Queue进行由线程完成或调用的manage task(方法)
您可以使用LIFO队列,优先级队列,FIFO队列detail
第二,添加一个类方法,以便可以将新方法或任务添加到队列中
将以下代码添加到您的代码中:
from queue import Queue
# or
# from multiprocessing import Queue
class my_thread(threading.Thread):
queue = Queue()
@classmethod
def add_task(cls,callable_task):
cls.queue.put(callable_task)
def startt(self):
print("it is going to wait forever")
while not self.stopped():
#wait forever, this part is going to run again and again
if not self.queue.empty():
_m = self.queue.get()
# do what ever you want to do with _m
print("This line never executes")
表示停止线程
Class my_thread(Threading.Thread)
stop_event = threading.Event()
@classmethod
def stop_thread(cls)
cls.stop_event.set()
def startt(self):
print("it is going to wait forever")
cls = self.__class__
while not cls.stop_event.is_set():
#wait forever, this part is going to run again and again
if not self.queue.empty():
_m = self.queue.get()
# do what ever you want to do with _m
print("This line never executes")
现在请求停止therad
my_thread.stop_thread()
<强> Exapmle 强>
import threading
import time
class my_thread(threading.Thread):
stop_event = threading.Event()
@classmethod
def stop_thread(cls):
cls.stop_event.set()
def run(self):
print("running the thread")
print("start function startt()")
self.__class__.stop_event.clear()
self.startt()
def startt(self):
print("it is going to wait forever")
cls = self.__class__
print cls.stop_event.is_set()
while not cls.stop_event.is_set():
pass
print("This line never executes")
a = my_thread()
a.start()
time.sleep(0.5)
my_thread.stop_thread()
print "\n\n\n"
b = my_thread()
b.start()
time.sleep(0.5)
my_thread.stop_thread()