2
# !/usr/bin/python3

import asyncio
import aiohttp
from threading import Thread


event_loop = asyncio.get_event_loop() # getting the event_loop
Thread(target=event_loop.run_forever).start() # creating one more thread(to add and then to execute tasks when it is necessary)


async def fetch(session, url): # exm/doc code from aiohttp lib.
    async with session.get(url) as response:
        return await response.text()


async def main(): # exm/doc code from aiohttp lib.
    async with aiohttp.ClientSession() as session:
        html = await fetch(session, 'http://python.org')
        print(html)


event_loop.create_task(main()) # doesn't work when the event_loop is already running... Is it the only way to add task before running the event_loop in asyncio?

The goal is to add task when it is necessary. For example, the main thread is for listening to a server and the second one is for responding. P.s this is only a small part of all code/

Am I doing something wrong or the asyncio library does not support this?

1
  • there is no reason to use Threading to make a call to run_forever for your event_loop. also since you are using Python 3.7 the preferred method of running your program should be asyncio.run(main()) Commented Jul 17, 2020 at 11:47

1 Answer 1

2

Am I doing something wrong

Yes. Since asyncio is not thread-safe, you cannot interact with the event loop from outside the thread that runs the event loop. The correct way to create the task is:

asyncio.run_coroutine_threadsafe(main(), event_loop)

See also the call_soon_threadsafe on the event loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.