return value in a python thread

In your setup that is a little difficult because you have no reference to the thread. So

  1. After starting it when is the thread ready?
  2. Where to are the results returned?

1 can be fixed by assigning the thread to a variable. 2 in your case you can provide an external list for the results and pass it as argument.

import threading
import time


def test_thread(list):

    for i in range(10):
        list.append(str(i))


my_list = []

my_thread = threading.Thread(target=test_thread, args=[my_list])
my_thread.start()

while my_thread.is_alive():
    time.sleep(0.1)

print(my_list)

Result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top