我正试图以并行方式进行一些绘图,以更快地完成大批量工作。为此,我为我计划制作的每一个绘图开始一个线程。
我曾希望每个线程都能完成它的绘图并关闭自己(据我所知,Python在完成run()中的所有语句后会关闭线程)。下面是一些显示这种行为的代码。
如果创建图的那一行被注释掉,它就会如期运行。另一个看似有帮助的花絮是,当你只生成一个线程时,它也能如期运行。
import matplotlib.pyplot as plt
import time
import Queue
import threading
def TapHistplots():
## for item in ['str1']:
# # it behaves as expected if the line above is used instead of the one below
for item in ['str1','str2']:
otheritem = 1
TapHistQueue.put((item, otheritem))
makeTapHist().start()
class makeTapHist(threading.Thread):
def run(self):
item, otheritem = TapHistQueue.get()
fig = FigureQueue.get()
FigureQueue.put(fig+1)
print item+':'+str(fig)+'\n',
time.sleep(1.3)
plt.figure(fig) # comment out this line and it behaves as expected
plt.close(fig)
TapHistQueue = Queue.Queue(0)
FigureQueue = Queue.Queue(0)
def main():
start = time.time()
"""Code in here runs only when this module is run directly"""
FigureQueue.put(1)
TapHistplots()
while threading.activeCount()>1:
time.sleep(1)
print 'waiting on %d threads\n' % (threading.activeCount()-1),
print '%ds elapsed' % (time.time()-start)
if __name__ == '__main__':
main()
任何帮助都是值得赞赏的。