- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章Python multiprocessing多进程原理与应用示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
本文实例讲述了Python multiprocessing多进程原理与应用。分享给大家供大家参考,具体如下:
multiprocessing包是Python中的多进程管理包,可以利用multiprocessing.Process对象来创建进程,Process对象拥有is_alive()、join([timeout])、run()、start()、terminate()等方法.
multprocessing模块的核心就是使管理进程像管理线程一样方便,每个进程有自己独立的GIL,所以不存在进程间争抢GIL的问题,在多核CPU环境中,可以大大提高运行效率.
multiprocessing使用示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import
multiprocessing
import
time
import
cv2
def
daemon1(image):
name
=
multiprocessing.current_process().name
for
i
in
range
(
50
):
image
=
cv2.GaussianBlur(image, (
3
,
3
),
1
)
time.sleep(
0.1
)
print
'daemon1 done!'
cv2.imshow(
'daemon1'
, image)
def
daemon2(image):
name
=
multiprocessing.current_process().name
for
i
in
range
(
50
):
image
=
cv2.GaussianBlur(image, (
3
,
3
),
1
)
time.sleep(
0.5
)
print
'daemon2 done!'
cv2.imshow(
'daemon2'
, image)
if
__name__
=
=
'__main__'
:
t1
=
time.time()
number_kernel
=
multiprocessing.cpu_count()
print
'We have {0} kernels'
.
format
(number_kernel)
p1
=
multiprocessing.Process(name
=
'daemon1'
,
target
=
daemon1,args
=
(cv2.imread(
'./p1.jpg'
),))
p1.daemon
=
False
p2
=
multiprocessing.Process(name
=
'daemon2'
,
target
=
daemon2, args
=
(cv2.imread(
'./p2.jpg'
),))
p2.daemon
=
False
p1.start()
p2.start()
print
'p1 is {0}'
.
format
(p1.is_alive())
p1.terminate()
p1.join()
print
'p1 is {0}'
.
format
(p1.is_alive())
print
'p2 is {0}'
.
format
(p2.is_alive())
p2.join()
t2
=
time.time()
print
'!!!!!!!!!!!!!!!!!!!!OK!!!!!!!!!!!!!!!!!!!!!'
print
'total time is {0}'
.
format
(t2
-
t1)
print
'p1.exitcode = {0}'
.
format
(p1.exitcode)
print
'p2.exitcode = {0}'
.
format
(p2.exitcode)
|
multiprocessing中Process是一个类,用于创建进程,以及定义进程的方法,Process类的构造函数是:
1
|
def
__init__(
self
, group
=
None
, target
=
None
, name
=
None
, args
=
(), kwargs
=
{})
|
参数含义:
程序解读:
在multiprocessing中使用pool 。
如果需要多个子进程时,使用进程池(pool)来(自动)管理各个子进程更加方便:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
from
multiprocessing
import
Pool
import
os, time
def
long_time_task(name):
print
'Run task {0} ({1})'
.
format
(name,os.getpid())
start
=
time.time()
time.sleep(
3
)
end
=
time.time()
print
'Task {0} runs {1:.2f} seconds.'
.
format
(name,end
-
start)
if
__name__
=
=
'__main__'
:
print
'Parent process ({0})'
.
format
(os.getpid)
p
=
Pool()
for
i
in
range
(
12
):
p.apply_async(long_time_task, args
=
(i,))
print
'Waiting for all subprocesses done...'
p.close()
p.join()
print
'All subprocesses done.'
|
与Process类创建进程的方法不同,Pool是通过apply_async(func,args=(args))方法创建进程,一个进程池中能同时运行的任务数是机器上CPU核的总数量n_kernel,如果创建的子进程数大于n_kernel,则同时执行n_kernel个进程,这n_kernel中某个进程完成之后才会启动下一个进程.
p.close()
关闭进程池之后才能调用join()方法多个子进程间的通信 。
多个子进程间的通信要用到multiprocessing.Queue,Queue的特性是它是一个消息队列。比如有以下的需求,一个子进程向队列中写数据,另外一个进程从队列中取数据的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from
multiprocessing
import
Process, Queue
import
os, time, random
def
write(q):
for
value
in
[
'A'
,
'B'
,
'C'
]:
print
'Put {0} to queue...'
.
format
(value)
q.put(value)
time.sleep(random.random())
def
read(q):
while
True
:
if
not
q.empty():
value
=
q.get(
True
)
print
'Get {0} from queue.'
.
format
(value)
time.sleep(random.random())
else
:
break
if
__name__
=
=
'__main__'
:
q
=
multiprocessing.Queue()
pw
=
Process(target
=
write, args
=
(q,))
pr
=
Process(target
=
read, args
=
(q,))
pw.start()
pw.join()
pr.start()
pr.join()
|
Queue使用方法:
Queue.get(False)
,取不到值时触发异常:Empty;Queue.get(False)
,当队列满了时报错:Full;在进程池Pool中,使用Queue会出错,需要使用Manager.Queue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
from
multiprocessing
import
Process, Queue
import
os, time, random
def
write(q):
for
value
in
[
'A'
,
'B'
,
'C'
]:
print
'Put {0} to queue...'
.
format
(value)
q.put(value)
time.sleep(random.random())
def
read(q):
while
True
:
if
not
q.empty():
value
=
q.get(
True
)
print
'Get {0} from queue.'
.
format
(value)
time.sleep(random.random())
else
:
break
if
__name__
=
=
'__main__'
:
manager
=
multiprocessing.Manager()
q
=
manager.Queue()
p
=
Pool()
pw
=
p.apply_async(write, args
=
(q,))
time.sleep(
2
)
pr
=
p.apply_async(read, args
=
(q,))
p.close()
p.join()
if
not
q.empty():
print
'q is not empty...'
else
:
print
'q is empty...'
print
'OK'
if
not
q.empty():
print
'q is not empty...'
else
:
print
'q is empty...'
print
'done...'
|
父进程与子进程共享内存 。
定义普通的变量,不能实现在父进程和子进程之间共享:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
multiprocessing
from
multiprocessing
import
Pool
def
changevalue(n, a):
n
=
3.14
a[
0
]
=
5
if
__name__
=
=
'__main__'
:
num
=
0
arr
=
range
(
10
)
p
=
Pool()
p1
=
p.apply_async(changevalue, args
=
(num, arr))
p.close()
p.join()
print
num
print
arr[:]
|
结果输出num的值还是在父进程中定义的0,arr的第一个元素值还是0.
使用multiprocessing创建共享对象
1
2
3
4
5
6
7
8
9
10
11
12
|
import
multiprocessing
def
changevalue(n, a):
n.value
=
3.14
a[
0
]
=
5
if
__name__
=
=
'__main__'
:
num
=
multiprocessing.Value(
'd'
,
0.0
)
arr
=
multiprocessing.Array(
'i'
,
range
(
10
))
p
=
multiprocessing.Process(target
=
changevalue, args
=
(num, arr))
p.start()
p.join()
print
num.value
print
arr[:]
|
结果输出num的值是在子进程中修改的3.14,arr的第一个元素值更改为5.
共享内存在Pool中的使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import
multiprocessing
from
multiprocessing
import
Pool
def
changevalue(n, a):
n.value
=
3.14
a[
0
]
=
5
if
__name__
=
=
'__main__'
:
num
=
multiprocessing.Value(
'd'
,
0.0
)
arr
=
multiprocessing.Array(
'i'
,
range
(
10
))
p
=
Pool()
p1
=
p.apply_async(changevalue, args
=
(num, arr))
p.close()
p.join()
print
num.value
print
arr[:]
|
希望本文所述对大家Python程序设计有所帮助.
原文链接:https://blog.csdn.net/dcrmg/article/details/78231845 。
最后此篇关于Python multiprocessing多进程原理与应用示例的文章就讲到这里了,如果你想了解更多关于Python multiprocessing多进程原理与应用示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我正在通过 labrepl 工作,我看到了一些遵循此模式的代码: ;; Pattern (apply #(apply f %&) coll) ;; Concrete example user=> (a
我从未向应用商店提交过应用,但我会在不久的将来提交。 到目前为止,我对为 iPhone 而非 iPad 进行设计感到很自在。 我了解,通过将通用PAID 应用放到应用商店,客户只需支付一次就可以同时使
我有一个应用程序,它使用不同的 Facebook 应用程序(2 个不同的 AppID)在 Facebook 上发布并显示它是“通过 iPhone”/“通过 iPad”。 当 Facebook 应用程序
我有一个要求,我们必须通过将网站源文件保存在本地 iOS 应用程序中来在 iOS 应用程序 Webview 中运行网站。 Angular 需要服务器来运行应用程序,但由于我们将文件保存在本地,我们无法
所以我有一个单页客户端应用程序。 正常流程: 应用程序 -> OAuth2 服务器 -> 应用程序 我们有自己的 OAuth2 服务器,因此人们可以登录应用程序并获取与用户实体关联的 access_t
假设我有一个安装在用户设备上的 Android 应用程序 A,我的应用程序有一个 AppWidget,我们可以让其他 Android 开发人员在其中以每次安装成本为基础发布他们的应用程序推广广告。因此
Secrets of the JavaScript Ninja中有一个例子它提供了以下代码来绕过 JavaScript 的 Math.min() 函数,该函数需要一个可变长度列表。 Example:
当我分别将数组和对象传递给 function.apply() 时,我得到 NaN 的 o/p,但是当我传递对象和数组时,我得到一个数字。为什么会发生这种情况? 由于数组也被视为对象,为什么我无法使用它
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界. 这篇CFSDN的博客文章ASP转换格林威治时间函数DateDiff()应用由作者收集整理,如果你
我正在将列表传递给 map并且想要返回一个带有合并名称的 data.frame 对象。 例如: library(tidyverse) library(broom) mtcars %>% spl
我有一个非常基本的问题,但我不知道如何实现它:我有一个返回数据框,其中每个工具的返回值是按行排列的: tmp<-as.data.frame(t(data.frame(a=rnorm(250,0,1)
我正在使用我的 FB 应用创建群组并邀请用户加入我的应用群组,第一次一切正常。当我尝试创建另一个组时,出现以下错误: {"(OAuthException - #4009) (#4009) 在有更多用户
我们正在开发一款类似于“会说话的本”应用程序的 child 应用程序。它包含大量用于交互式动画的 JPEG 图像序列。 问题是动画在 iPad Air 上播放正常,但在 iPad 2 上播放缓慢或滞后
我关注 clojure 一段时间了,它的一些功能非常令人兴奋(持久数据结构、函数式方法、不可变状态)。然而,由于我仍在学习,我想了解如何在实际场景中应用,证明其好处,然后演化并应用于更复杂的问题。即,
我开发了一个仅使用挪威语的应用程序。该应用程序不使用本地化,因为它应该仅以一种语言(挪威语)显示。但是,我已在 Info.plist 文件中将“本地化 native 开发区域”设置为“no”。我还使用
读完 Anthony's response 后上a style-related parser question ,我试图说服自己编写单体解析器仍然可以相当紧凑。 所以而不是 reference ::
multicore 库中是否有类似 sapply 的东西?还是我必须 unlist(mclapply(..)) 才能实现这一点? 如果它不存在:推理是什么? 提前致谢,如果这是一个愚蠢的问题,我们深表
我喜欢在窗口中弹出结果,以便更容易查看和查找(例如,它们不会随着控制台继续滚动而丢失)。一种方法是使用 sink() 和 file.show()。例如: y <- rnorm(100); x <- r
我有一个如下所示的 spring mvc Controller @RequestMapping(value="/new", method=RequestMethod.POST) public Stri
我正在阅读 StructureMap关于依赖注入(inject),首先有两部分初始化映射,具体类类型的接口(interface),另一部分只是实例化(请求实例)。 第一部分需要配置和设置,这是在 Bo
我是一名优秀的程序员,十分优秀!