python 多进程
#coding=utf-8
import random
import time
from multiprocessing import Process
def sign(name):
print('%s is running' %name)
time.sleep(5)
print('%s end' % name)
def main():
t1 = Process(target=sign,args=('菊花茶',))
t2 = Process(target=sign,args=("东风破",))
t3 = Process(target=sign,args=("勇气",))
t4 = Process(target=sign,args=("第一次",))
t1.start()
t2.start()
t3.start()
t4.start()
if __name__ == "__main__":
main()
print("主进程")
(python37) [root@localhost python]# python test.py 主进程 菊花茶 is running 勇气 is running 东风破 is running 第一次 is running 东风破 end 菊花茶 end 第一次 end 勇气 end (python37) [root@localhost python]#
[root@localhost ~]# ps -ef|grep test.py root 4683 4078 0 09:04 pts/1 00:00:00 python test.py root 4684 4683 0 09:04 pts/1 00:00:00 python test.py root 4685 4683 0 09:04 pts/1 00:00:00 python test.py root 4686 4683 0 09:04 pts/1 00:00:00 python test.py root 4687 4683 0 09:04 pts/1 00:00:00 python test.py root 4691 4654 0 09:04 pts/0 00:00:00 grep --color=auto test.py [root@localhost ~]# ps -ef|grep test.py root 4693 4654 0 09:04 pts/0 00:00:00 grep --color=auto test.py [root@localhost ~]#
python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。Python提供了multiprocessing。
multiprocessing模块用来开启子进程,并在子进程中执行我们定制的任务(比如函数),multiprocessing模块的功能众多:支持子进程、通信和共享数据、执行不同形式的同步,提供了Process、Queue、Pipe、Lock等组件。
与线程不同,进程没有任何共享状态,进程修改的数据,改动仅限于该进程内

浙公网安备 33010602011771号