python基础教程:用map函数来完成Python并行任务的简单示例

本文介绍了如何使用Python的map函数进行并行任务处理,对比了传统的多线程/多进程编程方式,强调了map函数在并行计算中的高效性和简洁性,并给出了创建缩略图的并行处理示例。
摘要由CSDN通过智能技术生成

这篇文章主要介绍了用map函数来完成Python并行任务的简单示例,多线程和多进程编程的问题一直都是Python中的热点和难点,需要的朋友可以参考下
众所周知,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!'
  
def Producer():
  # Queue is used to share items between
  # the threads.
  queue = Queue.Queue()
  
  # Create an instance of the worker
  worker = Consumer(queue)
  # start calls the internal run() method to
  # kick off the thread
  worker.start()
  
  # variable to keep track of when we started
  start_time = time.time()
  # While under 5 seconds..
  while time.time() - start_time < 5:
    # "Produce" a piece of work and stick it in
    # the queue for the Consumer to process
    queue.put('something at %s' % time.time())
    # Sleep a bit just to avoid an absurd number of messages
    time.sleep(1)
  
  # This the "poison pill" method of killing a thread.
  queue.put('quit')
  # wait for the thread to close down
  worker.join
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值