fork download
#!/usr/bin/env python
import logging
import multiprocessing
import math
import numpy as np
import sys

from multiprocessing import JoinableQueue as Queue, Process as Thread
from matplotlib import pyplot as plt

dbg = multiprocessing.get_logger().info

def plot_figure(queue, dqueue):
    while True:
        nfig = queue.get()
        try:
            dbg("plot %s" % nfig)        
            x = np.arange(nfig*math.pi/100, 5+nfig*math.pi/100, 0.1);
            y = np.sin(x)

            f = plt.figure(nfig)
            ax = f.add_subplot(111)
            ax.plot(x, y)
            ax.set_title(str(nfig))
            f.savefig('%s.pdf' % nfig)
            plt.close(nfig)
            queue.task_done()
            dbg("done %s" % nfig)
        finally:
            dqueue.put(nfig)
        
def main():
    logger = multiprocessing.log_to_stderr()
    logger.setLevel(logging.INFO)

    nthreads = int(sys.argv[1]) if len(sys.argv) > 1 else 2
    nfig = int(sys.argv[2]) if len(sys.argv) > 2 else 10

    # start threads
    fqueue = Queue()
    dqueue = Queue()
    threads = [Thread(target=plot_figure, args=(fqueue, dqueue))
               for fig in xrange(nthreads)]

    dbg("start %d threads" % len(threads))
    for t in threads:
        t.daemon = True
        t.start()

    dbg("fill queue")
    for fig in xrange(nfig):
        fqueue.put(fig)

    dbg("wait for threads")
    for _ in xrange(nfig):
        dqueue.get()
    dbg("done")

if __name__=="__main__":
    main()
        
Success #stdin #stdout 0.02s 7436KB
stdin
Standard input is empty
stdout

Standard output is empty