the following code simulates the use of two threads to manage event loop:
import time
import asyncio
import threading
async def task(c, i):
for _ in range(i):
print(c)
await asyncio.sleep(1)
return i
def thread(loop): -sharp
asyncio.set_event_loop(loop)
asyncio.ensure_future(task("sub thread", 999))
loop.run_forever()
def main():
threading.Thread(target=thread, args=(asyncio.get_event_loop(), )).start()
-sharp
future = asyncio.ensure_future(task("main thread", 5))
while not future.done():
time.sleep(1)
print("main done: %s" % future.result())
if __name__ == "__main__":
main()
its child thread ( thread
function) sets and enables a task
task 999 times.
in the main thread, a task
task is added five times. I set up a While loop to check that the task has finished running, and if so, print out main done: 5
.
questions raised:
- is there any other solution for multithreaded event loop like this?
- in the five
task
tasks of the main function, I initially tried to userun_until_complete
to wait for the end of execution, but a conflict withrun_forever
resulted in aRuntimeError: This event loop is already running
error thrown, so is there any other way to block subsequent code execution besides using the While loop?
actual situation description:
I have a program that uses Synchronize + Asynchronous
, where the Synchronize program runs on the main thread and async runs on a child thread.
Synchronize and Asynchronous run independently, each performing its own functions. But sometimes you need to use asynchronous functions or methods in Synchronize and get results.