众所周知,Python的并行处理才能很不睬想。我认为如不雅不推敲线程和GIL的标准参数(它们大年夜多是合法的),其原因不是因为技巧不到位,而是我们的应用办法不恰当。大年夜多半关于Python线程和多过程的教材固然都很出色,然则内容繁琐冗长。它们切实其实袈溱开篇铺陈了很多有效信息,但往往都不会涉及真正能进步日常工作的部分。
经典例子
DDG上以“Python threading tutorial (Python线程教程)”为关键字的热点搜刮结不雅注解:几乎每篇文┞仿中给出的例子都是雷同的类+队列。
事实上,它们就是以下这段应用producer/Consumer来处理线程/多过程的代码示例:
- #Example.py
- '''
- Standard Producer/Consumer Threading Pattern
- '''
- import time
- import threading
- import Queue
- class Consumer(threading.Thread):
- def __init__(self, queue):
- threading.Thread.__init__(self)
- self._queue = queue
- def run(self):
- while True:
- # queue.get() blocks the current thread until
- # an item is retrieved.
- msg = self._queue.get()
- # Checks if the current message is
- # the "Poison Pill"
- if isinstance(msg, str) and msg == 'quit':
- # if so, exists the loop
- break
- # "Processes" (or in our case, prints) the queue item
- print "I'm a thread, and I received %s!!" % msg
- # Always be friendly!
- print 'Bye byes!'
推荐阅读
神经收集是有史以来创造的最优美的编程范式之⼀。在传统的编程⽅法中,我们告诉计算机做什么,把⼤问题分成很多小的、准肯定义的义务,计算机可以很轻易地履行。比拟之>>>详细阅读
本文标题:Python一行代码完成并行任务
地址:http://www.17bianji.com/lsqh/34782.html
1/2 1