[英]Unable to stop running Python thread
我有一个应用程序在特定的TCP端口上侦听,以处理接收到的请求( listen.py
)。 之后,我还有另一个( trigger.py
),它根据请求的参数触发相应的操作。
现在,假设操作A已触发( opA.py
)。 操作A使用辅助线程来启动( worker.py
)。 当用户请求listen.py
停止操作A时,应该停止启动的线程。
更新:
问题在于线程永远不会停止,因为问题出在trigger.py
。 代码退出后,OperationA实例将丢失。 因此,我永远无法调用stopOperation,因为它显示了AttributeError: 'NoneType' object has no attribute 'stopOperation'
关于如何解决这个问题的任何想法?
listen.py
from trigger import Trigger
'''
code to handle requests here:
1st: param -> 'start'
2nd: param -> 'stop'
'''
t = Trigger()
t.execute(param)
trigger.py
from opA import OperationA
class Trigger():
def execute(param):
opA = OperationA()
if param == 'start':
opA.startOperation()
elif param == 'stop':
opA.stopOperation()
opA.py
from worker import ThreadParam
class OperationThread(ThreadParam):
def run(self):
while (self.running == False):
'''
do something here
'''
class OperationA():
def _init__(self):
listenThread = OperationThread(self)
def startOperation(self):
self.listenThread.start()
def stopOperation(self):
if self.listenThread.isAlive() == True:
print 'Thread is alive'
self.listenThread.killSignal()
else:
print 'Thread is dead'
worker.py
from threading import Thread
class ThreadParam(Thread):
def __init__(self, _parent):
Thread.__init__(self)
self.parent = _parent
self.running = False;
def killSignal(self):
self.running = True;
最小有用的Trigger
可能看起来像这样:
class Trigger(object):
def __init__(self):
self.operation = None
def execute(self, command):
if command == 'start':
assert self.operation is None
self.operation = OperationA()
self.operation.start_operation()
elif command == 'stop':
self.operation.stop_operation()
self.operation = None
else:
print 'Unknown command', repr(command)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.