简体   繁体   中英

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. 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:

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.

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.

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.

You can run the code of your blocking function run inside the default executor of the loop. 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.

Also you should check Running Tasks Concurrently .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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