Juicy
Juicy

Reputation: 12520

Using a global list in a Thread object

I'm trying to make a simple thread that appends stuff to a global list and then print the results in the main thread after sleeping for a few seconds:

import time,threading

list_of_things = []

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def __run__(self):
        global list_of_things
        for i in range(0, 10):
            list_of_things.append('hello ' + str(i))


if __name__ == "__main__":
    mythread = MyThread()
    mythread.start()
    time.sleep(5)   
    print list_of_things 

The list is apparently empty even though I declared it global in the thread.

Upvotes: 0

Views: 1428

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52143

Rename your __run__ method to run. And also instead of calling time.sleep(5), you should call .join() on thread to keep the program waiting till thread finishes its job.

import threading

list_of_things = []

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global list_of_things
        for i in range(0, 10):
            list_of_things.append('hello ' + str(i))


if __name__ == "__main__":
    mythread = MyThread()
    mythread.start()
    mythread.join()
    print list_of_things 

Upvotes: 3

Related Questions