fork download
  1. #!/usr/bin/env python
  2. import logging
  3. import multiprocessing
  4. import math
  5. import numpy as np
  6. import sys
  7.  
  8. from multiprocessing import JoinableQueue as Queue, Process as Thread
  9. from matplotlib import pyplot as plt
  10.  
  11. dbg = multiprocessing.get_logger().info
  12.  
  13. def plot_figure(queue, dqueue):
  14. while True:
  15. nfig = queue.get()
  16. try:
  17. dbg("plot %s" % nfig)
  18. x = np.arange(nfig*math.pi/100, 5+nfig*math.pi/100, 0.1);
  19. y = np.sin(x)
  20.  
  21. f = plt.figure(nfig)
  22. ax = f.add_subplot(111)
  23. ax.plot(x, y)
  24. ax.set_title(str(nfig))
  25. f.savefig('%s.pdf' % nfig)
  26. plt.close(nfig)
  27. queue.task_done()
  28. dbg("done %s" % nfig)
  29. finally:
  30. dqueue.put(nfig)
  31.  
  32. def main():
  33. logger = multiprocessing.log_to_stderr()
  34. logger.setLevel(logging.INFO)
  35.  
  36. nthreads = int(sys.argv[1]) if len(sys.argv) > 1 else 2
  37. nfig = int(sys.argv[2]) if len(sys.argv) > 2 else 10
  38.  
  39. # start threads
  40. fqueue = Queue()
  41. dqueue = Queue()
  42. threads = [Thread(target=plot_figure, args=(fqueue, dqueue))
  43. for fig in xrange(nthreads)]
  44.  
  45. dbg("start %d threads" % len(threads))
  46. for t in threads:
  47. t.daemon = True
  48. t.start()
  49.  
  50. dbg("fill queue")
  51. for fig in xrange(nfig):
  52. fqueue.put(fig)
  53.  
  54. dbg("wait for threads")
  55. for _ in xrange(nfig):
  56. dqueue.get()
  57. dbg("done")
  58.  
  59. if __name__=="__main__":
  60. main()
  61.  
  62.  
Success #stdin #stdout 0.02s 7436KB
stdin
Standard input is empty
stdout

Standard output is empty