设为首页 加入收藏

TOP

Python多进程编程详解
2019-05-23 14:50:13 】 浏览:60
Tags:Python 进程 编程 详解

序. multiprocessing


1. Process


创建进程的类:Process([group [, target [, name [, args [, kwargs]]]]]),target表示调用对象,args表示调用对象的位置参数元组。kwargs表示调用对象的字典。name为别名。group实质上不使用。


方法:is_alive()、join([timeout])、run()、start()、terminate()。其中,Process以start()启动某个进程。


属性:authkey、daemon(要通过start()设置)、exitcode(进程在运行时为None、如果为–N,表示被信号N结束)、name、pid。其中daemon是父进程终止后自动终止,且自己不能产生新进程,必须在start()之前设置。


例1.1:创建函数并将其作为单个进程


运行结果:


p.pid: 2322
p.name: Process-1
p.is_alive: True
The time is Sun May  5 07:36:18 2019
The time is Sun May  5 07:36:21 2019
The time is Sun May  5 07:36:24 2019
The time is Sun May  5 07:36:27 2019
The time is Sun May  5 07:36:30 2019
[Finished in 15.2s]


Python多进程编程详解


例1.2:创建函数并将其作为多个进程


运行结果如下:


worker_2
worker_1
worker_3
The number of CPU is:1
child  p.name:Process-3 p.id2783
child  p.name:Process-1 p.id2781
child  p.name:Process-2 p.id2782
END!!!!!!!!!!!!!!!!!
end worker_1
end worker_2
end worker_3
[Finished in 4.1s]


Python多进程编程详解


例1.3:将进程定义为类


注:进程p调用start()时,自动调用run()


结果如下:


the time is Sun May  5 07:45:05 2019
the time is Sun May  5 07:45:08 2019
the time is Sun May  5 07:45:11 2019
the time is Sun May  5 07:45:14 2019
the time is Sun May  5 07:45:17 2019
[Finished in 15.1s]


Python多进程编程详解


例1.4:daemon程序对比结果


#1.4-1 不加daemon属性


结果如下:


end!
work start:Sun May  5 07:46:54 2019
work end:Sun May  5 07:46:57 2019
[Finished in 3.1s]


Python多进程编程详解


#1.4-2 加上daemon属性


结果如下:


end!
[Finished in 0.1s]


Python多进程编程详解


注:因子进程设置了daemon属性,主进程结束,它们就随着结束了。


#1.4-3 设置daemon执行完结束的方法


结果如下:


work start:Sun May  5 07:49:59 2019
work end:Sun May  5 07:50:02 2019
end!
[Finished in 3.1s]


Python多进程编程详解


待续,继续更新中......


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python函数search()和match()的区.. 下一篇Python Numpy 数组的基本操作示例

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目