How to recover the return of a function that was executed within a Thread in Python3?

Asked

Viewed 615 times

0

I need to run a function through a Thread only I’m not sure how to recover the return of this function. Below an example of how I want to do:

from threading import Thread
import time

def teste_thread():
  for k in range(5):
    print('Executando Thread')
    time.sleep(1)

  return 'Thread Executada com sucesso!' #Como faço para pegar esse retorno de função?


t = Thread(target=teste_thread)
t.start()

print('Isso foi colocado depois do inicio da Thread')

1 answer

1


You could use multiprocessing.pool import ThreadPool instead of from threading import Thread in its implementation? It would be as follows:

from multiprocessing.pool import ThreadPool
import time

pool = ThreadPool(processes=1)

def teste_thread():
  for k in range(5):
    print('Executando Thread')
    time.sleep(1)
  return 'Thread Executada com sucesso!'

def exec():
    async_call = pool.apply_async(teste_thread)
    print('Processando....')
    return async_call.get()

if __name__ == '__main__':
    print(exec())

I added the excerpt 'main' to be able to simulate the call to your operation.

  • Your solution solved my problem, thank you very much for your help.

  • I’m glad I could help. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.