在树莓派上运行两个线程的问题

时间:2018-10-11 15:31:33

标签: python multithreading sockets video-streaming streaming

我有一个流传输程序,该程序将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

1 个答案:

答案 0 :(得分:0)

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

一个明显的问题是该代码:

while 1:
   pass

执行busy loop。因此,它使用CPU资源,但没有实质性作用。您可以在此处用passwait for thread to finish替换sleep(0.1)(但是,这需要切换到threading模块)

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

通常使用profiler来检查您的程序在哪里花费时间。