线程对象问题

时间:2014-05-23 18:32:44

标签: python multithreading

当我致电threadObj时,我无法弄清楚线程对象isAlive无法使用stop()的原因。代码如下所述。

from threading import Thread

class workerThread(Thread):
  def __init__(self, _parent):
    Thread.__init__(self)
    self.parent = _parent
    self.active = False

  def run(self):
    while(self.active == False):
      print 'I am here'
    print 'and now I am here'

class imp():
  def __init__(self):
    self.threadObj = None

  def start(self):
    self.threadObj = workerThread(self)
    self.threadObj.start()

  def stop(self):
    if self.threadObj.isAlive() == True:
      print 'it is alive'

它说:AttributeError:' NoneType'对象没有属性' isAlive'

调用代码如下所示:

from filename import imp

filename = imp()
if option == 'A':
  filename.start()
elif option == 'B':
  filename.stop()

2 个答案:

答案 0 :(得分:1)

根据您发布的内容:

from filename import imp

filename = imp() # you create an object here
if option == 'A':
  # if option is B, you are not launching the Thread
  # another words, this start() method will not be executed
  filename.start() 
elif option == 'B':
  # At this moment threadObj is None
  # because it wasn't started
  filename.stop() 

我建议您使用ptd来查找此类错误:

from filename import imp

filename = imp()

import ptb
ptb.set_trace()

if option == 'A':
  filename.start()
elif option == 'B':
  filename.stop()

答案 1 :(得分:1)

您的问题似乎是您错误地认为您的线程在您的程序调用之间是持久的,这是不正确的。当您致电python callingCode.py A时,您的程序将运行并执行if option == 'A'代码块。然后它退出,你的线程被清理干净。第二次,当你调用python callingCode.py B时,永远不会创建线程。