简体   繁体   中英

Unable to stop running Python thread

I have an application listening on a specific TCP port to handle received requests ( listen.py ). After that, I have another one ( trigger.py ) that depending on the requested parameters triggers the respective operation.

Now, lets say the operation A was triggered ( opA.py ). Operation A uses a worker thread to start ( worker.py ). When the user request listen.py to stop operation A, the started thread is supposed to stop.

UPDATED:

The problem is that the thread is never stopped since the problem lies in trigger.py . The OperationA instance is lost once the code exits. So, I can never call stopOperation since it show me AttributeError: 'NoneType' object has no attribute 'stopOperation'

Any ideas of How to solve this?

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;

A minimal useful Trigger might look like this:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM