好的,假设我有一个继承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可以通过排队获得其值(value)。我怎么做?

最佳答案

听起来您似乎并不是真的希望ProcessStuffDoStuffClass继承,而是希望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

关于python - 如何通过无限循环继承线程类,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25903213/

10-13 08:39