python - 如何将其转换为在多进程中工作?
问题描述
我正在研究一个机器人,并希望在我的树莓派上进行所有处理。我开始研究看起来很有希望的多线程,但是当我尝试进行更多操作时,rpi 正在节流。
这是获取坐标并判断是向上向下还是向左向右移动的类。
我添加了从我的 main.py 文件中更改的变量
是否有可能让它在不同的 CPU 中工作,或者我应该改变我的方法?
Controller.py
from dataPointObject.dataPointObjectClass import *
import threading
class Drive:
def __init__(self, frameInfo=FrameInfo()):
self.facePoint = FacePoint() // changing from main.py
self.obstaclePoint = ObstaclePoint() // changing from main.py
self.frameInfo = frameInfo
self.isDetected = False // changing from main.py
self.stopped = False // changing from main.py
def start(self):
print('Started')
threading.Thread(name='Drive', target=self.drive).start()
threading.Thread(name='AdjustCamera', target=self.adjustCamera).start()
return self
def drive(self):
while not self.stopped:
while self.isDetected:
if self.facePoint.x+self.facePoint.w > self.frameInfo.frameWidthLimitR: # Right Screen Margin
print('LEFT')
elif self.facePoint.x < self.frameInfo.frameWidthLimitL: # Left Screen Margin
print('RIGHT')
def adjustCamera(self):
while not self.stopped:
while self.isDetected:
if self.facePoint.y < self.frameInfo.frameHeightLimitT: # Top Screen Margin
print('DOWN')
elif self.facePoint.y + self.facePoint.h > self.frameInfo.frameHeightLimitB: # Bottom Screen Margin
print('UP')
def stop(self):
self.isDetected = False
self.stopped = True
def faceDetected(self , isDetected = False):
self.isDetected = isDetected
def setFacePoint(self,facePoint):
self.facePoint = facePoint
这是我要调用以开始处理的函数。VideoGet 和 VideoShow 正在处理不同的线程
def start(source=0):
video_getter = VideoGet(source).start()
video_shower = VideoShow(video_getter.frame , video_getter.frameInfo).start()
drive = Drive(frameInfo = video_getter.frameInfo).start()
while True:
drive.faceDetected(video_shower.facePoint != FacePoint())
drive.setFacePoint(video_shower.facePoint)
if video_getter.stopped or video_shower.stopped:
video_shower.stop()
video_getter.stop()
drive.stop()
break
frame = video_getter.frame
video_shower.frame = frame
解决方案
在命令行中通过 top 命令检查 %CPU。如果它在 100% 左右,那么程序只使用单核。Python 线程受 GIL 限制,要使用所有可用的 cpu,我们必须使用多处理而不是多线程。
或者,如果 rpi 因高温而节流,那么您可以在 while roop 中放置适当的毫秒时间睡眠(如 time.sleep(0.02) )。这是一个非常简单的解决方案,并且有效。
推荐阅读
- python - 在 python 中将 BytesIO 添加到 BytesIO tar.gz
- python - 将列表元素附加到另一个列表的函数返回空列表/元组
- python - 如何映射字符串列表和整数列表并找到具有最大价值的字符串
- mysql - SQL 中的 NULL 在以下场景中如何工作?
- java - 如何使用 ByteBuddy 创建没有公共构造函数的类的动态代理
- c# - 如何从文本框向数组添加值?WinForms C#
- ios - 如果预构建脚本在 create-keychain 之前运行,我如何使用 MS AppCenter 签署对讲框架?
- python - 从 ckeditor_uploader.fields 导入 RichTextUploadingField
- android-studio - 即使没有错误也无法运行我的项目
- java - spring-cloud-stream 的 DLQ 的分区 Kafka 主题