唔…….感到有点像Java。
我如今并不想解释应用Producer / Consume来解决线程/多过程的办法是缺点的——因为它肯定精确,并且在很多情况下它是最佳办法。但我不认为这是日常平凡写代码的最佳选择。
它的问题地点(小我不雅点)
起首,你须要创建一个样板式的铺垫类。然后,你再创建一个队列,经由过程其传递对象和监管队列的两妒攀来完成义务。(如不雅你想实现数据的交换或存储,平日还涉及另一个队列的介入)。
Worker越多,问题越多。
Map按序处理这些迭代。调用这个函数,它就会返回给我们一个按序存储着结不雅的简略单纯列表。
接下来,你应当会创建一个worker类的pool来进步Python的速度。下面是IBM tutorial给出的较好的办法。这也是法度榜样员们在应用多线程检索web页面时的常用办法。
- #Example2.py
- """
- A more realistic thread pool example
- """
- import time
- import threading
- import Queue
- import urllib2
- class Consumer(threading.Thread):
- def __init__(self, queue):
- threading.Thread.__init__(self)
- self._queue = queue
- def run(self):
- while True:
- content = self._queue.get()
- if isinstance(content, str) and content == "quit":
- break
- response = urllib2.urlopen(content)
- print "Bye byes!"
- def Producer():
- urls = [
- "http://www.python.org', 'http://www.yahoo.com",
- "http://www.scala.org', 'http://www.google.com",
- # etc..
推荐阅读
神经收集是有史以来创造的最优美的编程范式之⼀。在传统的编程⽅法中,我们告诉计算机做什么,把⼤问题分成很多小的、准肯定义的义务,计算机可以很轻易地履行。比拟之>>>详细阅读
本文标题:Python一行代码完成并行任务
地址:http://www.17bianji.com/lsqh/34782.html
1/2 1