一行 Python 实现并行化 — 日常多线程操作的新思路
admin
2023-07-30 22:25:28
0

Python 在程序并行化方面多少有些声名狼藉。撇开技术上的问题,例如线程的实现和 GIL1,我觉得错误的教学指导才是主要问题。常见的经典 Python 多线程、多进程教程多显得偏“重”。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。

传统的例子

简单搜索下“Python 多线程教程”,不难发现几乎所有的教程都给出涉及类和队列的例子:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 #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() if __name__ == \’__main__\’:    Producer()

哈,看起来有些像 Java 不是吗?

我并不是说使用生产者/消费者模型处理多线程/多进程任务是错误的(事实上,这一模型自有其用武之地)。只是,处理日常脚本任务时我们可以使用更有效率的模型。

问题在于…

首先,你需要一个样板类;
其次,你需要一个队列来传递对象;
而且,你还需要在通道两端都构建相应的方法来协助其工作(如果需想要进行双向通信或是保存结果还需要再引入一个队列)。

worker 越多,问题越多

按照这一思路,你现在需要一个 worker 线程的线程池。下面是 一篇 IBM 经典教程 中的例子——在进行网页检索时通过多线程进行加速。

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 #Example2.py\’\’\’A more realistic thread pool example \’\’\’hibo.net/2014/02/01/parallelism-in-one-line/#fn-616:1\”>1,我觉得错误的教学指导才是主要问题。常见的经典 Python 多线程、多进程教程多显得偏“重”。而且往往隔靴搔痒,没有深入探讨日常工作中最有用的内容。

传统的例子

简单搜索下“Python 多线程教程”,不难发现几乎所有的教程都给出涉及类和队列的例子:

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 #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() if __name__ == \’__main__\’:    Producer()

哈,看起来有些像 Java 不是吗?

我并不是说使用生产者/消费者模型处理多线程/多进程任务是错误的(事实上,这一模型自有其用武之地)。只是,处理日常脚本任务时我们可以使用更有效率的模型。

问题在于…

首先,你需要一个样板类;
其次,你需要一个队列来传递对象;
而且,你还需要在通道两端都构建相应的方法来协助其工作(如果需想要进行双向通信或是保存结果还需要再引入一个队列)。

worker 越多,问题越多

按照这一思路,你现在需要一个 worker 线程的线程池。下面是 一篇 IBM 经典教程 中的例子——在进行网页检索时通过多线程进行加速。

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 #Example2.py\’\’\’A more realistic thread pool example \’\’\’ /span> import time import threading import Queue import urllib2  class Consumer(threading.Thread

相关内容

热门资讯

500 行 Python 代码... 语法分析器描述了一个句子的语法结构,用来帮助其他的应用进行推理。自然语言引入了很多意外的歧义,以我们...
定时清理删除C:\Progra... C:\Program Files (x86)下面很多scoped_dir开头的文件夹 写个批处理 定...
65536是2的几次方 计算2... 65536是2的16次方:65536=2⁶ 65536是256的2次方:65536=256 6553...
Mobi、epub格式电子书如... 在wps里全局设置里有一个文件关联,打开,勾选电子书文件选项就可以了。
scoped_dir32_70... 一台虚拟机C盘总是莫名奇妙的空间用完,导致很多软件没法再运行。经过仔细检查发现是C:\Program...
pycparser 是一个用... `pycparser` 是一个用 Python 编写的 C 语言解析器。它可以用来解析 C 代码并构...
小程序支付时提示:appid和... [Q]小程序支付时提示:appid和mch_id不匹配 [A]小程序和微信支付没有进行关联,访问“小...
python绘图库Matplo... 本文简单介绍了Python绘图库Matplotlib的安装,简介如下: matplotlib是pyt...
Prometheus+Graf... 一,Prometheus概述 1,什么是Prometheus?Prometheus是最初在Sound...
微信小程序使用slider实现... 众所周知哈,微信小程序里面的音频播放是没有进度条的,但最近有个项目呢,客户要求音频要有进度条控制,所...