language: Python (python 2.7.3)
date: 861 days 16 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/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()