我目前尝试使用线程编写一个更大的python程序,并遇到了数组不必被声明为全局的问题。Python中的线程和全局变量 - 数组和标准变量之间的区别?
import numpy as np
import threading
import time
import ctypes
import multiprocessing
import random
import os
def child1():
#global var
starttime = time.time()
for ite in range(10):
#data_np[ite] = time.time()-starttime
#print data_np[ite]
var += 1
print var
time.sleep(1)
def child2():
#global var
for ite in range(10):
#print data_np
print var
print "\n"
time.sleep(1)
os.system("clear")
data_np = np.zeros(shape=(10), dtype="float")
var = 0
thread1 = threading.Thread(target=child1)
thread2 = threading.Thread(target=child2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
由于var未被声明为全局变量,因此上述代码将产生错误消息。 Unnotement
global var
产生一个可执行脚本,打印var的值两次。 但是用numpy的阵列data_np,没有声明需要
global data_np
时。脚本将运行。 我不明白这种行为。有人可以对此作出解释吗?
2015-07-21
kM00n