运行 raspberry pi 上的两个线程有​​问题

problem with running two threads on raspberry pi

我有一个流媒体程序,可以将 picamera 拍摄的视频帧从树莓派发送到服务器,还有另一个程序可以从服务器接收一些字符。当我单独 运行 它们时没有问题,但我希望它们同时 运行 它们执行某些功能,例如当 'a' 在服务器上按下时,所以我对它们进行了线程化,但这使得流式传输很慢.有解决这个问题的方法吗?

server.py:

def get_input(c):
    #getting input characters from keyboard and send them to raspberry 
def get_video(c):
    #getting video frames form raspberry 

thread.start_new_thread(get_video, ("2",))
thread.start_new_thread(get_input, ("1",))

while 1:
    pass

raspberry.py:

def get_input(c):
    #getting input chars from server
def send_video(c):
    #sending video frames to server

thread.start_new_thread(send_video, ("2",))
thread.start_new_thread(get_input, ("1",))

while 1:
    pass

为了解决问题,您首先需要找出问题的原因。

这里一个明显的问题是这段代码:

while 1:
   pass

执行 busy loop. So it uses CPU resources but does nothing substantial. You may replace pass with sleep(0.1) there or wait for thread to finish (this would require however to switch to threading 模块)

另一个可能的问题可能是 get_input 中的类似问题(您尚未显示其来源)。确保您在那里没有任何忙碌的等待。一些小的 sleep(50-100 毫秒)应该足以让其他线程有时间执行并且不会对用户体验造成太大影响。

一般使用profiler来检查你的程序在哪里花费时间。