相关文章推荐
眉毛粗的毛衣  ·  AttributeError: ...·  4 周前    · 
瘦瘦的棒棒糖  ·  OpenCV 4基础篇| ...·  5 小时前    · 
纯真的柑橘  ·  Visual Studio中编译.cu ...·  1 年前    · 
完美的抽屉  ·  .NET 中的 Json ...·  2 年前    · 

Matplotlib:在多线程中同时绘图

30 人关注

我正试图以并行方式进行一些绘图,以更快地完成大批量工作。为此,我为我计划制作的每一个绘图开始一个线程。

我曾希望每个线程都能完成它的绘图并关闭自己(据我所知,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()

任何帮助都是值得赞赏的。

3 个评论
你实际上没有说是什么地方出了问题,尽管这听起来像是某种线程并发问题。
我实际上不确定哪里出了问题。我没有得到任何错误,一个Python进程继续运行。另外,主线程中的打印语句应该每秒钟一次,但在第一秒后就没有了。在任务管理器中查看,该进程继续使用大量的cpu。不幸的是,我在认真调试方面的经验有限。
你打算多次调用 makeTapHist().start() 吗?看起来,也许它应该在循环之外。
python
multithreading
matplotlib
python-multithreading
Boris
Boris
发布于 2011-01-12
2 个回答
Joe Kington
Joe Kington
发布于 2011-01-12
已采纳
0 人赞同

为什么不直接使用多进程?就我从你的描述来看,线程对你没有什么帮助,反正...

Matplotlib已经有了线程,这样你就可以同时显示和交互多个数字。如果你想在多核机器上加快批处理速度,无论如何你都需要多处理。

作为一个基本的例子( 警告。这将在你运行它的任何目录中创建20个小的.png文件! )

import multiprocessing
import matplotlib.pyplot as plt
import numpy as np
def main():
    pool = multiprocessing.Pool()
    num_figs = 20
    input = zip(np.random.randint(10,1000,num_figs), 
                range(num_figs))
    pool.map(plot, input)
def plot(args):
    num, i = args
    fig = plt.figure()
    data = np.random.randn(num).cumsum()
    plt.plot(data)
    plt.title('Plot of a %i-element brownian noise sequence' % num)
    fig.savefig('temp_fig_%02i.png' % i)
main()