并发:交替执行任务(例如单核CPU)
并行:任务数小于等于CPU数量,每个CPU单独负责一个任务
进程:正在运行的程序,索要硬件资源(例如一个实验室)
线程:真正执行程序的单位(例如实验室中的每个打工人)
在Python中,创建子进程可以使用multiprocessing包,如下:
注意:
1. 进程之间不共享数据,哪怕是全局变量(子进程是主进程的副本)
2. 进程之间执行无序
import multiprocessing
import time
def time_consuming_task1():
for i in range(5):
print(f'I\'m doing task1 {i} now')
time.sleep(1)
def time_consuming_task2():
for i in range(10):
print(f'I\'m doing task2 {i} now')
time.sleep(0.5)
task1 = multiprocessing.Process(target=time_consuming_task1)
if __name__ == '__main__':
task1.start() # 子进程
time_consuming_task2() # 主进程
这里的if __name__ == '__main__'是必须的(在windows中必须,否则会报错:这是由于windows也会拷贝创建子进程的代码,于是子子孙孙无穷尽;但是linux与mac无需)
RuntimeError:
An attempt has been made to start a new process before the
current process has finished its bootstrapping phase.
This probably means that you are not using fork to start your
child processes and you have forgotten to use the proper idiom
in the main module:
if __name__ == '__main__':
freeze_support()
...
The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce an executable.
multiprocessing.Process 的主要参数
group: 必须为None
target: 函数或方法
name: 进程别名
args: 以元组方式传入的参数(按顺序)
kwargs: 以字典方式传参(按参数名)