七仔的博客

七仔的博客GithubPages分博

0%

【“魔镜”系列】多进程和进程间通信

因为python多线程并不是并行执行,因此较适合与I/O密集型程序,多进程并行执行适用于CPU密集型程序,我们的四个模块相对更适合多进程

【“魔镜”系列】多进程和进程间通信

选择多进程的原因

因为python多线程并不是并行执行,因此较适合与I/O密集型程序,多进程并行执行适用于CPU密集型程序,我们的四个模块相对更适合多进程

多进程的启动

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
#!/usr/bin/python3
from multiprocessing import Process, Queue
from lib import configurationUtil

import core.view_html.view_html as view_html
import core.face_detection.face_detection as face_detection
import core.dialogue.snowboy as snowboy
import core.sensor.sensor as sensor


def start():
print("Start to 4 process...")
try:
# 获取用户id
user_id = configurationUtil.get_user_id()
# 队列
queue = Queue()
# 启动显示视图线程
print("Start the view html process")
p_viw_html = Process(target=view_html.viw_html, args=(queue,))
p_viw_html.start()
# 启动人脸识别线程
print("Start the face recognition process")
p_face_detection = Process(target=face_detection.face_detection)
p_face_detection.start()
# 启动语音识别线程
print("Start the speech recognition process")
p_snowboy = Process(target=snowboy.snowboy, args=(user_id, queue))
p_snowboy.start()
# 启动传感器线程
print("Start the sensor process")
p_sensor = Process(target=sensor.sensor, args=(user_id, queue))
p_sensor.start()
except Exception as e:
print("Unexpected error:", e)
while 1:
pass

启动了四个进程,分别是视图、人脸识别、智能对话和温湿度传感器
我们来看传感器进程

1
2
3
4
# 启动传感器线程
print("Start the sensor process")
p_sensor = Process(target=sensor.sensor, args=(user_id, queue))
p_sensor.start()

sensor.sensor是函数名,user_id, queue是两个参数

进程间通信

选用队列Queue进程进行通信,我们关注queue这个参数

1
2
3
4
5
6
7
from multiprocessing import Process, Queue
# 队列
queue = Queue()
...
p_viw_html = Process(target=view_html.viw_html, args=(queue,))
...
p_sensor = Process(target=sensor.sensor, args=(user_id, queue))

可以看到queue这个参数被放到视图进程的第一个参数和传感器进程的第二个参数中

在传感器进程的代码中有这样的代码

1
2
3
4
5
json_data = {
"type": "sensor_data",
"data": data
}
queue.put(json_data)

这是发送消息,在视图进程有这样的代码

1
json_data = queue.get()

这是接收代码,非常简单明了

此为博主副博客,留言请去主博客,转载请注明出处:https://www.baby7blog.com/myBlog/73.html

欢迎关注我的其它发布渠道