无法将线程分配给局部变量

时间:2014-09-08 12:45:48

标签: python multithreading

我在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()

另外,这里是saltGatWayThread的源代码:

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

此外,我在src/proc/__init__.py中有以下代码:

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

在控制台中,我注意到self.currentThread为空。

我的目的是在启动时将线程保存在局部变量中。如果我收到中止请求,我会申请      stopRunning功能。这个功能,将采取保存的线程,并将“清理”退出(完成胎面和退出的过程)。

为什么我不能保存线程,并在以后使用它的结构?

1 个答案:

答案 0 :(得分:1)

调用currentThread = saltGatWayThread()然后调用.start()。 currentThread不包含线程实例,因为starts()方法总是根据threading.py源代码返回任何内容。请参阅C:\ Python27 \ Lib \ threading.py的源代码     def start(self):         msgstr“”“开始线程的活动。

    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()