我不知道为什么注释掉第七行时输出不同。代码如下:
#!/usr/bin/python
import threading
import time
def loop(thread_name):
if False:
print "1111" #The print is only used to prove this code block indeed not excute
global dict_test # The output will be different when commenting this line code
else:
dict_test = {}
i = 0
while i < 10:
i+=1
print "thread %s %s" % (thread_name,id(dict_test))
time.sleep(1)
t1=threading.Thread(target=loop,args=('1'))
t2=threading.Thread(target=loop,args=('2'))
t1.start()
t2.start()
t1.join()
t2.join()
如果解释是不管匹配哪个条件都预编译全局变量,为什么下面的代码会报错?
#!/usr/bin/python
import threading
import time
def loop(thread_name):
if False:
print "1111" #The print is only used to prove this code block indeed not excute
global dict_test # The output will be different when commenting or uncommenting this line code
else:
# dict_test = {}
pass
i = 0
while i < 10:
i+=1
print "thread %s %s" % (thread_name,id(dict_test))
time.sleep(1)
t1=threading.Thread(target=loop,args=('1'))
t2=threading.Thread(target=loop,args=('2'))
t1.start()
t2.start()
t1.join()
t2.join()