python - 线程对象问题

标签 python multithreading

当我调用 stop() 时,我不明白为什么线程对象 threadObj 不能使用 isAlive。代码说明如下。

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

最佳答案

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

关于python - 线程对象问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23836211/

相关文章:

python - 在 Ubuntu 14.04 VPS 上部署基本的 Python 3.4 Flask 应用程序

python - 使用 matplotlib 绘制点数图

java - Rest API 调用可在极短的时间内从多个 API 提供商获取数据 : Example websites like makemytrip

c# - 我能否将一个查询拆分为多个查询或创建并行机制以加快查询速度?

Python mysqldb db.commit() 不工作

python - 无法使用 Eclipse IDE 在 Python-Django 上创建 super 用户帐户?

python - 如果数据有缺失值,则 scipy.mstats.theilslopes 置信限度错误

c++ - 不同类上的互斥锁

C++线程概念

java - 当高吞吐量(3GB/s)文件系统可用时,如何在 Java 中使用多线程读取文件