29

大規模なバッチジョブをより迅速に完了するために、いくつかのプロットを並行して実行しようとしています。この目的のために、作成する予定のプロットごとにスレッドを開始します。

各スレッドがプロットを終了し、それ自体を閉じることを期待していました (私が理解しているように、Python は run() 内のすべてのステートメントを通過するとスレッドを閉じます)。以下は、この動作を示すコードです。

Figure を作成する行がコメント アウトされている場合、期待どおりに実行されます。もう 1 つの有益なヒントは、スレッドを 1 つだけ生成しても期待どおりに動作することです。

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()

どんな助けでも正当に評価されます。

4

2 に答える 2

31

マルチプロセッシングを使用しないのはなぜですか?とにかく、あなたの説明からわかる限り、スレッド化はあまり役に立ちません...

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()
于 2011-01-11T20:51:20.433 に答える
6

pylabインターフェイスには、ソリューションAsynchronous plotting with threadsがあります。

そうしないpylabと、matplotlib のバックエンド (Qt、GTK、WX、Tk) ごとに異なるソリューションが存在する可能性があります。問題は、各 GUI ツールキットにそれぞれ独自の GUI メインループがあることです。あなたはそれをどのようipythonに扱っているかを見ることができました。

于 2011-01-11T18:00:41.080 に答える