基本与threading相同
代码演示
import os
from multiprocessing import Process
import time
def task(num, name):
print(os.getpid(), "开始运行", num, name)
time.sleep(1)
print(os.getpid(), "结束运行")
if __name__ == '__main__':
for i in range(5):
p = Process(target=task, args=(i,), kwargs={"name": i**2})
p.start()
示例1
import os
import time
from multiprocessing import Pool
def task(num):
print(os.getpid(), "开始运行", num)
time.sleep(1)
print(os.getpid(), "结束运行")
if __name__ == '__main__':
pool = Pool(4)
p_list = []
for i in range(10):
p_list.append(pool.apply_async(task, args=(i,)))
for p in p_list:
p.wait()
实例2:回调函数
import os
import time
from multiprocessing import Pool
def back(res):
print(os.getpid(), "处理来自", res, "的结果")
def task(num):
print(os.getpid(), "开始运行", num)
time.sleep(1)
print(os.getpid(), "结束运行")
return os.getpid()
if __name__ == '__main__':
pool = Pool(4)
p_list = []
for i in range(10):
p_list.append(pool.apply_async(task, args=(i,), callback=back))
for p in p_list:
p.wait()