在 Thread 对象中使用全局列表

Using a global list in a Thread object

我正在尝试制作一个简单的线程,将内容附加到全局列表,然后在睡眠几秒钟后在主线程中打印结果:

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 

尽管我在线程中将其声明为全局列表,但该列表显然是空的。

将您的 __run__ 方法重命名为 run。此外,您应该在线程上调用 .join() 而不是调用 time.sleep(5),以使程序等待线程完成其工作。

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