3
3
Multiprocess
4
4
============
5
5
6
- Demo of using multiprocessing for generating data in one process and plotting
7
- in another.
6
+ Demo of using multiprocessing for generating data in one process and
7
+ plotting in another.
8
8
9
9
Written by Robert Cimrman
10
10
"""
11
-
12
11
from __future__ import print_function
13
- from six .moves import input
14
12
15
13
import time
16
- from multiprocessing import Process , Pipe
17
14
import numpy as np
18
15
19
- import matplotlib
20
- matplotlib .use ('GtkAgg' )
16
+ from multiprocessing import Process , Pipe
17
+
18
+ # This example will likely not work with the native OSX backend.
19
+ # Uncomment the following lines to use the qt5 backend instead.
20
+ #
21
+ # import matplotlib
22
+ # matplotlib.use('qt5Agg')
23
+
21
24
import matplotlib .pyplot as plt
22
- import gobject
23
25
24
26
# Fixing random state for reproducibility
25
27
np .random .seed (19680801 )
26
28
29
+ ###############################################################################
30
+ #
31
+ # Processing Class
32
+ # ================
33
+ #
34
+ # This class plots data it recieves from a pipe.
35
+ #
36
+
27
37
28
38
class ProcessPlotter (object ):
29
39
def __init__ (self ):
@@ -55,18 +65,36 @@ def __call__(self, pipe):
55
65
56
66
self .pipe = pipe
57
67
self .fig , self .ax = plt .subplots ()
58
- self .gid = gobject .timeout_add (1000 , self .poll_draw ())
68
+ timer = self .fig .canvas .new_timer (interval = 1000 )
69
+ timer .add_callback (self .poll_draw ())
70
+ timer .start ()
59
71
60
72
print ('...done' )
61
73
plt .show ()
62
74
75
+ ###############################################################################
76
+ #
77
+ # Plotting class
78
+ # ==============
79
+ #
80
+ # This class uses multiprocessing to spawn a process to run code from the
81
+ # class above. When initialized, it creates a pipe and an instance of
82
+ # ``ProcessPlotter`` which will be run in a separate process.
83
+ #
84
+ # When run from the command line, the parent process sends data to the spawned
85
+ # process which is then plotted via the callback function specified in
86
+ # ``ProcessPlotter:__call__``.
87
+ #
88
+
63
89
64
90
class NBPlot (object ):
65
91
def __init__ (self ):
66
92
self .plot_pipe , plotter_pipe = Pipe ()
67
93
self .plotter = ProcessPlotter ()
68
- self .plot_process = Process (target = self .plotter ,
69
- args = (plotter_pipe ,))
94
+ self .plot_process = Process (
95
+ target = self .plotter ,
96
+ args = (plotter_pipe ,)
97
+ )
70
98
self .plot_process .daemon = True
71
99
self .plot_process .start ()
72
100
@@ -84,8 +112,8 @@ def main():
84
112
for ii in range (10 ):
85
113
pl .plot ()
86
114
time .sleep (0.5 )
87
- input ('press Enter...' )
88
115
pl .plot (finished = True )
89
116
117
+
90
118
if __name__ == '__main__' :
91
119
main ()
0 commit comments