简体   繁体   English

如何在 Python asyncio 事件循环中手动启动和停止运行阻塞代码的线程?

[英]How to manually start and stop a thread running blocking code within a Python asyncio event loop?

I have an app that runs in asyncio loop.我有一个在 asyncio 循环中运行的应用程序。 I wish to start a thread which will execute a piece of blocking code:我希望启动一个线程来执行一段阻塞代码:

def run(self)->bool:
        self._running = True
        while self._running:
        
            #MOVE FORWORD / BACKWORDS
            if kb.is_pressed('x'):
                self.move_car("forward")
            elif kb.is_pressed('w'):
                self.move_car("backward")
            
        return True

until I decide to stop it and manually set the self._running = False by calling:直到我决定停止它并通过调用手动设置self._running = False

def stop(self):
    self._running = False

These are both methods of a class controlling the whole operation of a raspberry pi robot-car I made.这些都是 class 控制我制作的树莓派机器人汽车的整个操作的两种方法。

I want this to run on a separate thread so that my main application can still listen to my input and stop the thread while the other thread is running in this while loop you can see above.我希望它在一个单独的线程上运行,以便我的主应用程序仍然可以监听我的输入并停止线程,而另一个线程正在这个 while 循环中运行,您可以在上面看到。

How can I achieve that?我怎样才能做到这一点? Note For sending the start and stop signal I use http requests but this does not affect the core of my question.注意对于发送启动和停止信号,我使用http请求,但这不会影响我问题的核心。

You can run the code of your blocking function run inside the default executor of the loop.您可以在循环的默认执行程序中run阻塞 function 的代码。 This is documented here Executing code in thread or process pools .此处记录了在线程或进程池中执行代码

async def main():
    # asumming you have a class `Interface`
    # that conatins `run` and an async method `listen_for_stop`.
    loop = asyncio.get_running_loop()
    inter = Interface()  
    run_task = loop.run_in_executor(None, inter.run)
    results = await asyncio.gather(run_task, inter.listen_for_stop())

I couldn't test this code but I hope it clarifies what you can do.我无法测试这段代码,但我希望它能阐明你能做什么。 With asyncio.gather you await for the execution of the two tasks concurrently.使用asyncio.gather您可以同时等待两个任务的执行。

Also you should check Running Tasks Concurrently .您还应该检查同时运行任务

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

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