无法停止运行Python线程

时间:2014-07-10 18:05:13

标签: python multithreading

我有一个应用程序侦听特定的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;

1 个答案:

答案 0 :(得分:0)

最小有用的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)