【发布时间】:2016-11-20 19:10:21
【问题描述】:
我想为消费者生产者实现一个。我还没有实现消费者,因为我对生产者有问题。目的是在互联网上下载一些文件。线程在自定义对象的方法中启动。线程是 threading.Thread 的子类对象。这是代码
downloader_thread.py
from threading import Thread
import time
class Downloader(Thread):
def __init__(self, queue, out_queue):
super(Downloader, self).__init__()
self.queue = queue
self.out_queue = out_queue
def run(self):
while True:
page = self.queue.get()
if page:
print "Simulating download"
print "Downloading page ", page
time.sleep(3)
self.out_queue.put(page)
self.queue.task_done()
main_class.py
from Queue import Queue
from downloader_thread import Downloader
class Main(object):
def __init__(self):
self.queue = Queue(0)
self.out_queue = Queue(0)
self.threads = []
self.max_threads = 5
def download(self):
page = 1
for i in range(self.max_threads):
download_thread = Downloader(self.queue, self.out_queue)
download_thread.setDaemon(True)
download_thread.start()
self.threads.append(download_thread)
while page < 100:
self.queue.put(page)
page += 1
self.queue.join()
for thread in self.threads:
thread.join()
if __name__ == "__main__":
main = Main()
main.download()
while not main.out_queue.empty():
print main.out_queue.get()
问题是线程正常启动所有五个,它们执行 run 方法中的内容,但不要停止,所以 while 永远不会被执行。我对线程和并发编程有点陌生,所以请温柔:)
关键是要有一个消费者线程来处理代码的while部分,而不是在“main”中处理这个while:部分代码
【问题讨论】:
标签: python multithreading queue producer-consumer