0

I've created a python class that extends threading and uses a library that runs asyncio tasks.

import threading
from app.food import recipes

class Mixer(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    
    async def run(self):
        while True:
           ingredients = await recipes.get()
   

When I run the code I get following error:

RuntimeWarning: coroutine 'Mixer.run' was never awaited

Any ideas how to solve it?

Thanks

1 Answer 1

1

run in Thread class is not supposed to be a coroutine. It is just called as is. Not waited for. It is called obj.run() not by a await obj.run() nor asyncio.run(self.run) or whatever.

When you extend a class, you are supposed to overload methods while keeping the same interface (that's the whole point of extending/overloading). Here, you are not. Your are replacing a method that is meant to be just ran, by a one that is supposed to be awaited.

What exactly are you trying to do? There are already, in asyncio, some functions to transform a (implicit) thread into a coroutine (for non-asyncio blocking tasks, that you want to "await"). See to_thread() method, for example. Or other functions to interact with threads. Depending on what you are really trying to do here.

10
  • I am going to use the ThreadPoolExecutor to execute the asyncio task.
    – sam
    Commented Oct 4, 2022 at 9:44
  • I am not very familiar with that. But I doubt it requires "Thread" with awaitable runs. (I put quotes around "Thread", because Thread with awaitable runs are no longer Threads). In fact, at first glance to ThreadPoolExecutor, they seems to be to be another implementation of asyncio tasks (maybe they are internally implemented with async/await. Or with threads. But in example codes, I don't see any mention neither of asyncio, await, async, nor of thread module. It looks like it is transparent to the user)
    – chrslg
    Commented Oct 4, 2022 at 9:53
  • In your case, I get that you have a recipes.get method that takes a while (probably because it is getiting things from internet), and you don't want to block waiting it.
    – chrslg
    Commented Oct 4, 2022 at 9:54
  • For that, you could use ThreadPoolExecutor, and simply pass a plain, old, normal, blocking function, without any async/await or threads. That "recipe.get()" and block. And threadpoolexecutor will make it concurrent for you (probably, I take that from the name, by lauching each task in a thread)
    – chrslg
    Commented Oct 4, 2022 at 9:56
  • Or you could do that yourself, by creating a thread that does recipe.get(), lauching several of them yourself if needed, and then joining them.
    – chrslg
    Commented Oct 4, 2022 at 9:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.