Section 116.1: 运行两个简单进程

  • 使用多进程的一个简单例子是两个进程(工作进程)分别执行。在以下示例中,启动了两个进程:
    • countUp() 每秒向上计数 1。
    • countDown() 每秒向下计数 1。
import multiprocessing
import time
from random import randint

def countUp():
  i = 0
  while i <= 3:
    print('Up:\t{}'.format(i))
    time.sleep(randint(1, 3)) # 随机休眠 1、2 或 3 秒
    i += 1

def countDown():
  i = 3
  while i >= 0:
    print('Down:\t{}'.format(i))
    time.sleep(randint(1, 3)) # 随机休眠 1、2 或 3 秒
    i -= 1

if __name__ == '__main__':
  # 初始化工作进程。
  workerUp = multiprocessing.Process(target=countUp)
  workerDown = multiprocessing.Process(target=countDown)

  # 启动工作进程。
  workerUp.start()
  workerDown.start()

  # 等待工作进程完成。这将在主(父)进程中阻塞,
  # 直到工作进程完成。
  workerUp.join()
  workerDown.join()

The output is as follows:

Up: 0
Down: 3
Up: 1
Up: 2
Down: 2
Up: 3
Down: 1
Down: 0

运行两个简单进程

Section 116.2: 使用 Pool 和 map

from multiprocessing import Pool

def cube(x):
  return x ** 3

if __name__ == "__main__":
  pool = Pool(5)
  result = pool.map(cube, [0, 1, 2, 3])

Pool 是一个类,它在后台管理多个 Worker(进程),并让你(程序员)使用。Pool(5) 创建了一个包含 5 个进程的新 Pool,而 pool.map 的工作方式类似于内置的 map 函数,但它使用多个进程(在创建 Pool 时定义的数量)。

类似的实现可以通过 map_async、apply 和 apply_async 来完成,这些方法可以在文档中找到。