我想尝试在并行中进行一些绘图操作,以便更快地完成大批量的工作。为此,我为每个要进行的绘图启动一个线程。
我曾希望每个线程都能完成其绘图并关闭自己(据我所知,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()
非常感谢您的帮助。
makeTapHist().start()
吗?看起来它应该放在循环体外面。 - Mad Physicist