我试图多线程化我的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...
当我调试代码并逐行逐行时,它似乎正在工作,但一旦线程关闭,线程的所有结果都将丢失。如何将结果返回主线程?
答案 0 :(得分:1)
您可以使用队列:
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()
答案 1 :(得分:0)
这比我想象的容易得多。据我所知,你不必返回任何东西,发送给线程的对象与源代码相同。