在下面的代码中,我希望saveData函数同时执行48次。我正在使用线程来实现这一点,但程序不是保存文件,而是打印经过的时间并在执行后立即退出。为什么saveData函数没有被执行?我怎么能做到这一点?
#!/usr/bin/env python
import sys
import numpy as np
import h5py
import scipy
from PIL import Image
import timeit
import thread
import matplotlib.pyplot as plt
def saveImage(array, filename):
fig=plt.figure(figsize=(4,3))
ax=fig.add_subplot(1,1,1)
plt.axis('off')
p = plt.imshow(array)
p.set_cmap('gray')
extent = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
plt.savefig(filename, bbox_inches=extent)
def saveData(value1, value2, value3, dset):
filename = "tomo1_" + str(value1) + ".png"
data = dset[value1,:,:]
saveImage(data, filename)
filename = "tomo2_" + str(value2) + ".png"
data = dset[:,value2,:]
saveImage(data, filename)
filename = "tomo3_" + str(value3) + ".png"
data = dset[:,:,value3]
saveImage(data, filename)
def run():
# Reopen the file and dataset using default properties.
f = h5py.File(sys.argv[1])
dset = f[sys.argv[2]]
dim1 = len(dset)
dim2 = len(dset[0])
dim3 = len(dset[0][0])
slice1 = 0
slice2 = 0
slice3 = 0
factor1 = dim1/48
factor2 = dim2/48
factor3 = dim3/48
tic=timeit.default_timer()
for i in range(0,48):
thread.start_new_thread(saveData,(slice1, slice2, slice3, dset))
slice1 = slice1 + factor1
slice2 = slice2 + factor2
slice3 = slice3 + factor3
toc=timeit.default_timer()
print "elapsed time: " + str(toc - tic)
if __name__ == "__main__":
run()
答案 0 :(得分:2)
首先,建议您使用友好模块“threading”而不是低级模块“thread”。
其次,你需要等待线程完成他们的工作。如果你使用threading.Thread对象,它有一个“join”方法,你可以用它来确保你的线程在你的代码进展之前完成。
看一下这个答案的例子:
答案 1 :(得分:1)
手头的问题是你的父线程完成了,但是没有检查是否还有正在运行的子线程,这些线程以这种方式被静默杀死!我建议采用以下方法:
而不是import thread
使用import threading
更改你的线程代码:
thread.start_new_thread(saveData,(slice1, slice2, slice3, dset))
到
threads_running = [] # keep track of your threads
# thread starting loop
for i in xrange(48): # in this case xrange is what you really want!
... # do your data preparations here (slice, etc.)
thread = threading.Thread(target=saveDate,
args=(slice1, slice2, slice3, dset))
thread.start()
threads_running.append(thread) # "register" the running thread
# thread waiting to finish loop
while threads_running:
thread = thread_lst[i]
thread.join(0.1) # wait 0.1 second for thread to finish
if thread.is_alive(): # else check next thread
continue
else:
print "Thread %s finished" % threads_running.pop(i)
类似的回答question。