Python3 asyncio is used in threads

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 .

< hr >

questions raised:

  1. is there any other solution for multithreaded event loop like this?
  2. in the five task tasks of the main function, I initially tried to use run_until_complete to wait for the end of execution, but a conflict with run_forever resulted in a RuntimeError: This event loop is already running error thrown, so is there any other way to block subsequent code execution besides using the While loop?
< hr >

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.

Mar.20,2021

you don't need to call future.done (), in a loop with future.result ().

I suggest putting eventloop in the main thread, and other work-dependent types can be placed in

  1. same (main) thread
    non-blocking (non-CPU operation) actions, such as asyncio.sleep
  2. from thread (pool)
    block (non-CPU operation) actions, such as time.sleep
  3. separate processes
    CPU arithmetic actions, such as calculating prime numbers
< H2 > reference < / H2 >

python.org/3/library/asyncio-dev.html-sharpconcurrency-and-multithreading" rel=" nofollow noreferrer "> https://docs.python.org/3/lib.
python.org/moin/GlobalInterpreterLock" rel= "nofollow noreferrer" > https://wiki.python.org/moin/.

< H2 > example < / H2 >
-sharp -*- coding: utf-8 -*-
import asyncio
from datetime import datetime


async def add(a, b):
    await asyncio.sleep(1)
    return a + b


async def master_thread(loop):
    print("{} master: 1+2={}".format(datetime.now(), await add(1, 2)))


def slave_thread(loop):
    -sharp : coroutine 
    import time
    time.sleep(2)

    f = asyncio.run_coroutine_threadsafe(add(1, 2), loop)
    print("{} slave: 1+2={}".format(datetime.now(), f.result()))


async def main(loop):
    await asyncio.gather(
        master_thread(loop),
        -sharp 
        loop.run_in_executor(None, slave_thread, loop),
    )


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))
    loop.close()
Menu