return
return

Reputation: 301

Python - list not populated while thread is alive

I created two simple functions to see how threads are working. I want to populate a list while a thread is alive. But the list returned is empty.

def test_function():
    x=1
    while x<=100000:
        x=x+1


def thread_function(funct):
    t = threading.Thread(target=funct)
    t.start()
    l = []
    while t.isAlive():
        l.append(datetime.datetime.now())
    return l

print(thread_function(test_function())) #returns []

Upvotes: 0

Views: 84

Answers (2)

omri_saadon
omri_saadon

Reputation: 10621

You need to pass the function test_function instead of the returned value of this function test_function(), which is None.

So, basically the function that you give as a target to the thread is None.

Change this :

print(thread_function(test_function())) 

To:

print(thread_function(test_function))

Upvotes: 1

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140148

That's because you're executing test_function in the main thread, and pass None to your thread_function instead of the function itself.

print(thread_function(test_function()))

should be

print(thread_function(test_function))

Upvotes: 1

Related Questions