作家
登录

Python一行代码完成并行任务

作者: 来源: 2017-04-14 10:02:25 阅读 我要评论

众所周知,Python的并行处理才能很不睬想。我认为如不雅不推敲线程和GIL的标准参数(它们大年夜多是合法的),其原因不是因为技巧不到位,而是我们的应用办法不恰当。大年夜多半关于Python线程和多过程的教材固然都很出色,然则内容繁琐冗长。它们切实其实袈溱开篇铺陈了很多有效信息,但往往都不会涉及真正能进步日常工作的部分。

经典例子

DDG上以“Python threading tutorial (Python线程教程)”为关键字的热点搜刮结不雅注解:几乎每篇文┞仿中给出的例子都是雷同的类+队列。

事实上,它们就是以下这段应用producer/Consumer来处理线程/多过程的代码示例:

  1. #Example.py 
  2.  
  3. ''
  4.  
  5.     Standard Producer/Consumer Threading Pattern 
  6.  
  7. ''
  8.  
  9.   
  10.  
  11. import time 
  12.  
  13. import threading 
  14.  
  15. import Queue 
  16.  
  17.   
  18.  
  19. class Consumer(threading.Thread): 
  20.  
  21. def __init__(self, queue): 
  22.  
  23.     threading.Thread.__init__(self) 
  24.  
  25.     self._queue = queue 
  26.  
  27.   
  28.  
  29. def run(self): 
  30.  
  31.     while True
  32.  
  33.         # queue.get() blocks the current thread until 
  34.  
  35.         # an item is retrieved. 
  36.  
  37.         msg = self._queue.get() 
  38.  
  39.         # Checks if the current message is 
  40.  
  41.         # the "Poison Pill" 
  42.  
  43.         if isinstance(msg, str) and msg == 'quit'
  44.  
  45.             # if so, exists the loop 
  46.  
  47.             break 
  48.  
  49.         # "Processes" (or in our case, prints) the queue item 
  50.  
  51.         print "I'm a thread, and I received %s!!" % msg 
  52.  
  53.         # Always be friendly! 
  54.  
  55.     print 'Bye byes!' 
  56.  
     1/8    1 2 3 4 5 6 下一页 尾页

      推荐阅读

      理解深度学习的钥匙 –启蒙篇

    神经收集是有史以来创造的最优美的编程范式之⼀。在传统的编程⽅法中,我们告诉计算机做什么,把⼤问题分成很多小的、准肯定义的义务,计算机可以很轻易地履行。比拟之>>>详细阅读


    本文标题:Python一行代码完成并行任务

    地址:http://www.17bianji.com/lsqh/34782.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)