简体   繁体   English

如何使用并行使用两个循环的Python?

[英]How to use use two loops parallel, Python?

I am working on motion detection application in Raspberry Pi. 我正在研究Raspberry Pi中的运动检测应用程序。 There is a python script which should check output of c++ code and if "alert" is printed, it should start to upload images from a given directory to server: 有一个Python脚本应该检查c++代码的输出,如果打印了“ alert”,它应该开始将图像从给定目录上载到服务器:

for line in self.output:
  if line == "alert\n":
    # upload a frame from directory to a server

However, each frame takes around 30 seconds to upload to a server, but each new line is printed out in 500ms. 但是,每帧要花费大约30秒才能上载到服务器,但是每行都需要500毫秒才能打印出来。 So, it is not efficient at all to wait for uploading current frame in each if condition of for loop. 因此,它是不是在所有有效地等待每个上传当前帧if条件for循环。

I am new to Python. 我是Python的新手。 Is there any way to run two methods parallel? 有什么办法可以并行运行两个方法吗? I know about threads, but I am not sure what would happen if for loop creates new thread each time in Raspberry Pi. 我知道线程,但是我不确定每次在Raspberry Pi中for循环创建新线程时会发生什么。

each time you execute a the if statement a thread will be created, it would execute and then stop(if the thread itself doesn't have a loop). 每次执行if语句时,都会创建一个线程,该线程将执行然后停止(如果线程本身没有循环)。 you can use the following syntax. 您可以使用以下语法。

    def myFunc():
         #does the stuff you want it to do 
    for line in self.output:
       if line == "alert\n":
          threading.Thread(target=myFunc,args=randomArgs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM