如何继承具有无限循环的线程类

时间:2014-09-18 02:24:00

标签: python multithreading inheritance

好吧,假设我有一个继承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的代码可以通过排队获取其值。我该怎么做?

1 个答案:

答案 0 :(得分:3)

听起来您并不希望ProcessStuff继承DoStuffClass,而是希望ProcessStuff在内部使用DoStuffClass队列。因此,不要使用继承,只需让ProcessStuff在内部保留对DoStuffClass实例的引用,并使用内部Queue对象来获取DoStuffClass生成的值:

class ProcessStuff(Thread):
    def __init__(self, queue):
        super(ProcessStuff, self).__init__()
        self.queue = queue
        self._do_queue = Queue()  # internal Queue for DoStuffClass
        self._do_stuff = dostuff.DoStuffClass(self._do_queue)

    def run(self):
        self._do_stuff.startthread(True)
        self._do_stuff.start()
        while True:
            val = self._do_queue.get()  # Grab value from DoStuffClass
            # process it
            processed_val = "processed {}".format(val)
            self.queue.put(processed_val)

q = Queue(maxsize=1)
letsprocessstuff = ProcessStuff(q)

letsprocessstuff.start()
while (True):
    val = q.get()
    print "Outputting: %s" % val

输出:

Outputting: processed stream data
Outputting: processed stream data
Outputting: processed stream data
Outputting: processed stream data