Unde Clash
Unde Clash

Reputation: 13

I'm using asyncio but async function is blocking other async functions with await asyncio.sleep(5)

I've include asyncio to asynchronous my code in my library twbotlib (https://github.com/truedl/twbotlib).

I tried the asynced commands some versions ago and all go well, but I don't check about if is really asynced. Then I've tried to create a giveaway command and use await asyncio.sleep(5). I realized that is blocking all my other code...

After many tries to play with the asyncio code I don't reach the result is running without blocking...

(My class Bot in main.py have an attribute that called self.loop and is actually asyncio.get_event_loop)

I don't know if I do all correctly because I'm just after calling the Run function, I call all later operations with await.

I've tried to replace the just await with await self.loop.create_task(foo). I tried to do await self.loop.ensure_future(foo) but nothing...

Too I've tried to split the code to two functions (mainloop and check_data).

First of all in the code is the Run function here I start the loop (just creating task and run_forever):

    def run(self, startup_function=None) -> None:
        """ Run the bot and start the main while. """

        self.loop.create_task(self.mainloop(startup_function))
        self.loop.run_forever()

Secondly here the mainloop function (all the await functions are blocking...):

    async def mainloop(self, startup_function) -> None:
        """ The main loop that reads and process the incoming data. """

        if startup_function:
            await startup_function()

        self.is_running = True
        while self.is_running:
            data = self.sock.recv(self.buffer).decode('utf-8').split('\n')
            await self.check_data(data)

And the last one is the check_data (is splitted mainloop [I've replace the long if's with "condition" for readability], here too the await's is blocking):

    async def check_data(self, data: str) -> None:
        for line in data:
            if confition:
                message = self.get_message_object_from_str(line)
                if condition:
                    if condition:
                        await self.commands[message.command](message, message.args)
                    else:
                        await self.commands[message.command](message)
                elif hasattr(self.event, 'on_message'):
                    await self.event.on_message(message)
            if self.logs:
                print(line)

There is no error message. The code is blocking and I'm trying to change it to not block the code.

Upvotes: 1

Views: 554

Answers (1)

LiuXiMin
LiuXiMin

Reputation: 1265

The loop for line in data: is blocking you code.

Upvotes: 1

Related Questions