在python中同时执行方法

2024-09-28 22:10:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,我希望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()        

Tags: importdatadefsyspltfilenamethreadstr
2条回答

首先,建议您使用更友好的模块“threading”,而不是低级模块“thread”。你知道吗

其次,您需要等待线程完成它们的工作。如果你使用穿线。穿线对象,它有一个“join”方法,您可以使用该方法确保在代码进行之前线程已经完成。你知道吗

以这个答案为例:

https://stackoverflow.com/a/11968818/1055722

现在的问题是,父线程完成了,但是没有检查是否还有子线程仍在运行,这些子线程以这种方式被静默地终止!我建议采取以下办法:

使用import threading代替import thread

更改线程代码:

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。你知道吗

相关问题 更多 >