【发布时间】:2014-09-18 02:24:00
【问题描述】:
好的,假设我有一个继承 Thread 的工作类:
from threading import Thread
import time
class DoStuffClass(Thread):
def __init__(self, queue):
self. queue = queue
self.isstart = False
def startthread(self, isstart):
self.isstart = isstart
if isstart:
Thread.__init__(self)
else:
print 'Thread not started!'
def run(self):
while self.isstart:
time.sleep(1)
if self.queue.full():
y = self.queue.get() #y goes nowhere, it's just to free up the queue
self.queue.put('stream data')
我已经尝试在另一个文件中调用它并且它工作成功:
from Queue import Queue
import dostuff
q = Queue(maxsize=1)
letsdostuff= dostuff.DoStuffClass()
letsdostuff.startthread(True)
letsdostuff.start()
val = ''
i=0
while (True):
val = q.get()
print "Outputting: %s" % val
现在,我可以通过队列获取类输出的值。
我的问题:假设我想创建另一个继承 DoStuffClass 的类(ProcessStuff),以便我可以通过队列对象(或任何其他方法)获取 DoStuffClass 的输出,处理它,并将其传递给 ProcessStuff 的队列,所以调用 ProcessStuff 的代码可以通过排队获得它的值。我该怎么做?
【问题讨论】:
-
另外,请参阅this comment 我提出的另一个关于多线程的问题。如果您的线程正在执行 CPU 密集型操作,您最好使用
multiprocessing模块而不是threading。
标签: python multithreading inheritance