我正在尝试做一些并行绘图以更快地完成大批量作业。为此,我为每个我计划制作的情节开始一个线索。我希望每个线程都能完成它的绘图并关闭自己(据我所知,Python在run())中通过所有语句时会关闭线程)。以下是一些显示此行为的代码。Matplotlib:多线程同时绘图
如果创建图的线已被注释掉,则按预期运行。另一个看似有用的小技巧就是当你只生成一个线程时,它也能按预期运行。
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()
任何帮助都适当赞赏。
2011-01-11
Boris
+3
你实际上没有说什么不顺心,虽然这听起来像某种线程并发问题。 –
2011-01-11 16:19:50
+0
我并不确定会出现什么问题。我没有得到任何错误,并且python进程继续运行。另外,主线程中每秒应该关闭的print语句在第一秒之后不会这样做。任务管理器的外观表明该过程继续使用大量的CPU。不幸的是,我在严肃的调试方面经验有限。 –
2011-01-11 16:42:50
+0
你打算多次调用`makeTapHist()。start()`吗?看起来也许它应该在循环之外。 –
2016-01-20 18:22:21