python同时执行多个循环 [英] Python multiple loops at the same time

查看:925
本文介绍了python同时执行多个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在Python中不可能同时运行多个循环. 无论如何,我需要实现的是,我有一个循环运行,每0.25秒读取一次传感器数据负载. 同时,我有并行运行的信号设备,需要每3秒发送一次信号. 我的问题是最佳做法是通过什么方式实现的?

I know that it is not possible to run multiple loops at the same time in Python. Anyhow, what I need to achieve is that I have one loop running reading loads of sensor data, every 0.25 seconds. At the same time I have signal devices running in parallel that need to send signals every 3 seconds. My question is what way is best practice to achieve this?

编写两个脚本并并行运行它们是否有意义? 使用线程有意义吗? 为了使这项工作还有其他可能性吗?

Does it make sense to write two scripts and run them in parallel? Does it make sense to use threading? Is there any other possibility in order to make this work?

我将非常感谢代码示例.

I would be greatful for code samples.

谢谢!

两个循环都是绝对独立的. 因此,假设脚本1正在运行时,当其中一个传感器接收到的值≤时,读取传感器数据. 300,它应该运行脚本2,它将发送信号.同时,当传感器数据大于300时,应停止脚本2.

Both loops are absolutely independent. So, let's say while script 1 is running, reading the sensor data, when one of the sensors received a value < 300, it should run script 2 which will send the signals. At the same time when the sensors data gets > 300 it should stop script 2.

推荐答案

"Python同时出现多个循环.我知道这是不可能的[...]"-这看起来真的很有趣.

"Python multiple loops at the same time. I know that it is not possible [...]" - this looks really funny.

可以完全按照您的描述同时运行两个循环.两种方式都有意义,这取决于您实际需要和想要的东西.如果任务是完全独立的,则应将其作为两个脚本运行.如果您需要这两个循环来实现一项任务,并且将它们放在一个文件中很有意义,则可以使用

It is possible to run two loops at the same time, exactly how you described it. And both ways make much sense, depending on what do you actually need and want. If the tasks are completely independent you should run it as two scripts. If you need those two loops to realize one task and it makes sense for them to be in one file you can use multiprocessing.

经过python 2.7.5+和3.3.2+的测试.

Tested for python 2.7.5+ and 3.3.2+.

这是一些最小的示例:

from multiprocessing import Process
import time

def f(name):
    print('hello', name)
    time.sleep(10)

def d(name):
    print('test2', name)
    time.sleep(10)

if __name__ == '__main__':
    p1 = Process(target=f, args=('bob',))
    p2 = Process(target=d, args=('alice',))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

脚本运行10秒钟,两个字符串都立即打印出来,这意味着一切正常.

Script runs for 10s and both strings are printed right away, which means everything works.

time python3 ./process.py 
hello bob
test2 alice

real  0m10.073s
user  0m0.040s
sys   0m0.016s

这篇关于python同时执行多个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆