diff --git a/examples/misc/multiprocess.py b/examples/misc/multiprocess.py index 510e9001fa3e..38a67507b4ff 100644 --- a/examples/misc/multiprocess.py +++ b/examples/misc/multiprocess.py @@ -6,11 +6,12 @@ import time from multiprocessing import Process, Pipe import numpy as np - import matplotlib -matplotlib.use('GtkAgg') +# not all backends may allow safe plotting from multiple threads +# you can select a specific backend by uncommenting the line below +# and update the selected backend as needed +# matplotlib.use('QT5Agg') import matplotlib.pyplot as plt -import gobject class ProcessPlotter(object): @@ -21,35 +22,33 @@ def __init__(self): def terminate(self): plt.close('all') - def poll_draw(self): - - def call_back(): - while 1: - if not self.pipe.poll(): - break + def call_back(self): + while True: + if not self.pipe.poll(): + break - command = self.pipe.recv() + command = self.pipe.recv() - if command is None: - self.terminate() - return False + if command is None: + self.terminate() + return False - else: - self.x.append(command[0]) - self.y.append(command[1]) - self.ax.plot(self.x, self.y, 'ro') + else: + self.x.append(command[0]) + self.y.append(command[1]) + self.ax.plot(self.x, self.y, 'ro') - self.fig.canvas.draw() - return True - - return call_back + self.fig.canvas.draw_idle() + return True def __call__(self, pipe): print('starting plotter...') self.pipe = pipe self.fig, self.ax = plt.subplots() - self.gid = gobject.timeout_add(1000, self.poll_draw()) + timer = self.fig.canvas.new_timer(interval=1000) + timer.add_callback(self.call_back) + timer.start() print('...done') plt.show() @@ -78,8 +77,15 @@ def main(): for ii in range(10): pl.plot() time.sleep(0.5) - raw_input('press Enter...') + pl.plot(finished=True) if __name__ == '__main__': + # The default way to start a process on OSX ('fork') + # does not work well with many gui frameworks on OSX + # if you use Python 3.4 or later you can uncomment the + # two lines below to change the default start to + # forkserver. + # import multiprocessing as mp + # mp.set_start_method('forkserver') main()