[英]Python: return result from a thread
我正在嘗試對我的Python應用程序進行多線程處理。 這就是我認為應用程序可以工作的方式:
剛接觸Python並沒有多線程經驗,我嘗試過類似的方法:
import threading
import confDumper
class MyThread (threading.Thread):
device = None
# A device object is sent as agument
def __init__(self, device):
threading.Thread.__init__(self)
self.device = device
def run(self):
print "Starting scan..."
self.sshscan()
print "Exiting thread"
def sshscan(self):
s = confDumper.ConfDumper(self.device.mgmt_ip, self.device.username, self.device.password, self.device.enable_password)
t = s.getConf()
if t:
# We got the conf, return it to the main thread, somehow...
當我調試代碼並一步一步地遍歷每一行時,它似乎正在工作,但是一旦線程關閉,線程的所有結果都會丟失。 如何將結果返回主線程?
您可以使用隊列:
import Queue
import threading
import random
import time
class Worker(threading.Thread):
def __init__(self, queue):
super(Worker, self).__init__()
self._queue = queue
def run(self):
time.sleep(5.0 * random.random())
self._queue.put(str(self))
queue = Queue.Queue()
workers = [Worker(queue) for _ in xrange(10)]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
while queue.qsize():
print queue.get()
這比我想的要容易得多。 據我所知,您不必返回任何內容,發送給線程的對象與源相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.