[英]How to inherit a thread class with infinite loop
好吧,假設我有一個繼承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可以通過排隊獲得其價值。 我怎么做?
聽起來你並不真的希望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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.