O
O
Old_TyT2021-09-26 17:47:49
Python
Old_TyT, 2021-09-26 17:47:49

How to return the value of a function in a thread?

There is a code:

class get:
    def info(msgID):
        r = "321"
        print("def " + r)
        return(r)

class qwe:
    async def qqq(msgID):
        th = Thread(target=get.info, args=(msgID, ))
        th.start()
        print(th.join())

But the value from the stream comes "None", how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-09-26
@Old_TyT

" As join() always returns None... "
join() never returns anything other than None at all.
It's better to tell the thread where it should put the result.
For example, so

def thread_body(arg, target):
    result = "foo" + arg
    target.append(result)

def call_thread(arg):
    target = []
    th = threading.Thread(target=thread_body, args=(arg, target))
    th.start()
    th.join()
    return target[0]

But this code is synchronous. You have an asynchronous program, as far as I can see, and th.join() will block it.
It may make sense to either use run_in_executor() or refactor thread_body() to asynchronous code (if possible).
The executor will create a flow for you, by the way. Example at the link.
To get the loop object your async function is running in, use asyncio.get_running_loop() .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question