[英]How to run an infinite loop without blocking the main thread in Python?
I have a method in a class which opens a connection to an API and then listens for changes. 我在一个类中有一个方法,该方法打开与API的连接,然后侦听更改。 The listening for changes is done using an infinite for loop that receives events from a method in the library for API connections that I am using.
侦听更改是使用无限for循环完成的,该循环从库中的方法接收事件以用于我正在使用的API连接。 The only problem is that the infinite loop blocks the main thread, which needs to run other things.
唯一的问题是无限循环会阻塞主线程,而该主线程需要运行其他东西。 I have attempted to use threading, however the for loop needs access to variables in my class to set the changes received from the API.
我尝试使用线程,但是for循环需要访问类中的变量来设置从API接收的更改。 I need a way to run this infinite loop without blocking the main thread, but still being able to set class variables in a class in the main thread.
我需要一种在不阻塞主线程的情况下运行此无限循环的方法,但仍然能够在主线程的类中设置类变量。
Here is the loop that needs to be run: 这是需要运行的循环:
for event in events():
event_type = event.event
print(event_type)
if event_type == 'open':
pass
elif event_type == 'put':
# this sets the class variable
self._status = json.loads(event.data)
elif event_type == 'auth_revoked':
raise AuthorizationError(None, msg='The API authorization has been revoked')
elif event_type == 'error':
raise APIError(None, msg=event.data)
That's a tricky problem. 那是一个棘手的问题。
One approach would be to run the infinite loop in a separate thread, and set up a thread-safe mechanism for that thread to communicate with the main thread (eg by using Queues
to send data back and forth in a thread-safe manner, or mutexes
to make sure that one thread doesn't modify data while another thread is using it). 一种方法是在单独的线程中运行无限循环,并为该线程建立与主线程进行通信的线程安全机制(例如,通过使用
Queues
以线程安全的方式来回发送数据),或者mutexes
以确保一个线程在另一线程使用数据时不会修改数据)。
The alternative approach would be to use the library's API in a non-blocking manner such that you can integrate it with whatever event loop your main thread is already using. 另一种方法是以非阻塞方式使用库的API,以便您可以将其与主线程已在使用的任何事件循环集成在一起。 Whether or not that is possible will depend a lot on the API your library provides you to use;
能否实现将在很大程度上取决于您的库提供给您使用的API。 you might want to contact the authors of the library (or perhaps their developer's mailing list, if they have one) and ask them if there is a recommended way to handle this situation.
您可能需要与库的作者联系(或者如果有的话,与他们的开发人员的邮件列表联系),并询问他们是否有建议的方法来处理这种情况。
A third approach (which may or may not be practical in your case) would be to run the infinite loop, but on each iteration of the infinite loop call a function that runs one iteration of your main thread's normal event loop. 第三种方法(在您的情况下可能实用或可能不实用)是运行无限循环,但在无限循环的每次迭代中,调用一个函数运行主线程的正常事件循环的一次迭代。 (or vice versa).
(或相反亦然)。 That way each codebase gets to run one iteration of its codebase, then the other one gets to run one iteration, and so on, indefinitely.
这样,每个代码库都可以运行其代码库的一个迭代,然后另一个代码库可以无限期地运行一个,依此类推。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.