'How to do two tasks at the same time in asyncio or multithreading?
I'm trying to achieve a task that requires real-time interaction, for example: A message (response) is received - it needs to be acted on at the same time.
I tried the multi-threading module but couldn't really get to work, so I'm demonstrating an idea here as to what I'm intending to accomplish.
Here, a message "Hello" and "How are you?" needs to be outputted at the same time as it would in 2 separate threads.
This doesn't execute "Hi, how are you?" and just keeps outputting "Hello".
import asyncio
from time import sleep
async def respond():
while True:
sleep(1)
print("Hi, how are you?")
async def main():
asyncio.create_task(respond())
while True:
sleep(1)
print("Hello")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Yes, I need something like two threads because while one has a "loop" which is actively checking for a message - I want to create a task in another thread which will then send message to that loop to do the rest.
Solution 1:[1]
try to use python-worker (link)
import asyncio
from time import sleep
from worker import async_worker
@async_worker
async def respond():
while True:
sleep(1)
print("Hi, how are you?")
@async_worker
async def main():
await respond()
while True:
sleep(1)
print("Hello")
if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | danangjoyoo |
