我试图创建一个简单的线程,将东西附加到全局列表,然后在睡眠几秒钟后在主线程中打印结果:
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
即使我在线程中声明它是全局的,列表显然是空的。
答案 0 :(得分:3)
将__run__
方法重命名为run
。而且不是调用time.sleep(5)
,而是应该在线程上调用.join()
以保持程序等待,直到线程完成其工作。
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