How to retrieve the return of a function that was executed inside a Thread in Python3?

0

I need to run a function through a Thread only so I'm not sure how to retrieve the return from this function. Here's an example of how I want to do it:

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')
    
asked by anonymous 26.02.2018 / 22:21

1 answer

1

Could you use multiprocessing.pool import ThreadPool instead of from threading import Thread in your implementation? It would look like this:

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 ' main ' section to be able to simulate the call to your operation.

    
26.02.2018 / 22:55