我已经问过我的问题,但理解起来太复杂了。所以这是一个非常简单的问题。 我想要的是在python3中的类中使用线程的循环上进行流控制。 假设这段代码:
import threading
from time import sleep
class someclass(threading.Thread):
def __init__(self):
super(someclass, self).__init__()
self.stop_event = False
def poll(self):
print("your main function is running")
for i in range (0,50):
print("i=",i)
sleep(0.5)
def stop(self):
print("stopping the thread")
self.stop_event = True
def stopped(self):
return self.stop_event
def run(self):
print("stop_event: ",self.stop_event)
while not self.stopped():
for i in range (0,50):
print("i=",i)
sleep(0.5)
if __name__=='__main__':
thr=someclass()
print("starting the thread #1")
thr.start()
sleep(10)
print("stopping the thread #1")
thr.stop()
sleep(10)
thr2=someclass()
print("starting the thread #2")
thr2.start()
sleep(10)
print("stopping the thread #2")
thr2.stop()
sleep(10)
print("Exiting the whole program")
所以输出将是这样的:
starting the thread #1
stop_event: False
i= 0
i= 1
...
i= 17
i= 18
i= 19
stopping the thread #1
stopping the thread
i= 20
i= 21
i= 22
...
i= 38
i= 39
starting the thread #2
stop_event: False
i= 0
i= 40
i= 1
i= 41
i= 2
i= 42
i= 3
使用thr.stop()
停止线程后,它继续打印i内容,但self.stop_event
的值已设置为True。我想要的是随时控制一个循环,当然我希望它在一个不在我程序主体中的类中。
答案 0 :(得分:1)
答案 1 :(得分:0)
在@Gribouillis的帮助下,问题似乎已得到解决。我还需要说在一个线程中使用threading.Event
对象有一个无限循环不是一个好主意,如果你想启动一个线程的多个实例,它可以多次声明并且不要尝试启动/停止线程的唯一实例。
import threading
from time import sleep
class someclass(threading.Thread):
def __init__(self):
super(someclass, self).__init__()
self.stop_event = False
self.i=0
def poll(self):
print("your main function is running")
for i in range (0,50):
print("i=",i)
sleep(0.5)
def stop(self):
print("stopping the thread")
self.stop_event = True
def stopped(self):
return self.stop_event
def run(self):
print("stop_event: ",self.stop_event)
while not self.stopped():
#for i in range (0,50):
print("i=",self.i)
sleep(0.5)
self.i+=1
if __name__=='__main__':
thr=someclass()
print("starting the thread #1")
thr.start()
sleep(10)
print("stopping the thread #1")
thr.stop()
sleep(10)
thr2=someclass()
print("starting the thread #2")
thr2.start()
sleep(10)
print("stopping the thread #2")
thr2.stop()
sleep(10)
print("Exiting the whole program")