Or Smith
Or Smith

Reputation: 3596

Cant assign thread to local variable

I have the following code in python:

class gateWay:
   def __init__(self):
        self.var1 = []
        self.var2 = {}
        self.currentThread = None

   def stateProcess(self, file):
     # some irrelevant code 
     self.currentThread = saltGatWayThread(self, file).start()
     return self.var1

   def stopRunning(self):
      self.currentThread.proc.stop()

In addition, here the source code of the saltGatWayThread:

class saltGatWayThread(threading.Thread):
    def __init__(self):
       threading.Thread.__init__(self)
       # some irrelevant code
       self.proc = src.proc.Process1()

In addition, I have the following code in src/proc/__init__.py:

class Process1:
     def stop(self):
          # code to stop operation

In the console, I notice that self.currentThread is null.

My purpose is to save the thread in local variable, when start it. If I get an abort request, I apply stopRunning function. This function, would take the saved thread and will do "clean" exit (finish the process of the tread and exit).

Why can't I save the thread, and use the structure of it later on?

Upvotes: 0

Views: 77

Answers (1)

minskster
minskster

Reputation: 532

invoke currentThread = saltGatWayThread() and then call .start(). currentThread does not contains thread instance because starts() method always returns nothing according to the threading.py source code. See source of C:\Python27\Lib\threading.py def start(self): """Start the thread's activity.

    It must be called at most once per thread object. It arranges for the
    object's run() method to be invoked in a separate thread of control.

    This method will raise a RuntimeError if called more than once on the
    same thread object.

    """
    if not self.__initialized:
        raise RuntimeError("thread.__init__() not called")
    if self.__started.is_set():
        raise RuntimeError("threads can only be started once")
    if __debug__:
        self._note("%s.start(): starting thread", self)
    with _active_limbo_lock:
        _limbo[self] = self
    try:
        _start_new_thread(self.__bootstrap, ())
    except Exception:
        with _active_limbo_lock:
            del _limbo[self]
        raise
    self.__started.wait()

Upvotes: 1

Related Questions