简体   繁体   English

如果发生事件,则在Python中唤醒一个线程

[英]Wake up a thread in Python if event occurs

I know questions like this have already been asked, so in a sense, this is a duplicate. 我知道这样的问题已经被问过了,所以从某种意义上讲,这是一个重复的问题。 However, I've looked at many of those questions, and numerous websites, and I still can't figure out how to do what the title of this question says. 但是,我已经看过很多这样的问题,还有很多网站,我仍然无法弄清楚如何解决这个问题的标题。 This is what I'm trying to accomplish, more specifically: 这是我想要完成的,更具体地说:

One thread, t_sensors , reads values from a sensor, and after it does so, goes to sleep for refresh_rate amount of seconds. 一个线程, t_sensors ,从传感器中读取的值,它这样做之后,进入睡眠状态refresh_rate秒量。 This might be a few hours, so during this time it could get a request to read values from the sensor again. 这可能是几个小时,因此在此期间它可能会再次请求从传感器读取值。 This request comes from the thread t_checker , which checks for data in a Firebase database, and based on the data, chooses whether or not to wake up t_sensors . 此请求来自线程t_checker ,它检查Firebase数据库中的数据,并根据数据选择是否唤醒t_sensors

def start_sensors(self):
     # do some stuff...
     # refreshes every refresh_rate secs
     refresh_rate = firebase_root.get('/settings', 'refreshRate')
     condition.wait(refresh_rate)

 def check_for_plants(self):
     while True:
         modded_plants = firebase_root.get('/modifiedPlants', '')
         print(modded_plants)
         for plant, properties in modded_plants.items():
             print properties['status']
             if properties['status'] == 'modified':
                 condition.notify()
                 print("Notified")

 condition = threading.Condition()
 t_sensors = threading.Thread(target=start_sensors, args=(condition,))
 t_checker = threading.Thread(target=check_for_plants, args=(condition,))
 condition.acquire()
 t_sensors.start()
 t_checker.start()

I know I'm not using conditions correctly, at all, but I'm really not sure where I should even start fixing the problem. 我知道我根本没有正确使用条件,但我真的不确定我应该在哪里开始修复问题。 I'd really, really appreciate your help. 我真的非常感谢你的帮助。

In the end, I chose to avoid threads altogether... I found they were unnecessary. 最后,我选择完全避免线程......我发现它们是不必要的。 Instead, I passed the value of refresh_rate to check_for_plants() from start_sensors() , and then it slept in increments of 2 seconds until the time was up, or called start_sensors() if an event occurred. 相反,我将refresh_rate的值从start_sensors()传递给check_for_plants() ,然后以2秒的增量睡眠,直到时间结束,或者如果发生事件则调用start_sensors() Thank you so much for all the help! 非常感谢你的帮助!

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

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