运行两个简单的进程
使用多个进程的一个简单示例是两个单独执行的进程(worker)。在以下示例中,启动了两个进程:
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)) # sleep 1, 2 or 3 seconds
i += 1
def countDown():
i = 3
while i >= 0:
print('Down:\t{}'.format(i))
time.sleep(randint(1, 3)) # sleep 1, 2 or 3 seconds
i -= 1
if __name__ == '__main__':
# Initiate the workers.
workerUp = multiprocessing.Process(target=countUp)
workerDown = multiprocessing.Process(target=countDown)
# Start the workers.
workerUp.start()
workerDown.start()
# Join the workers. This will block in the main (parent) process
# until the workers are complete.
workerUp.join()
workerDown.join()
输出如下:
Up: 0
Down: 3
Up: 1
Up: 2
Down: 2
Up: 3
Down: 1
Down: 0