I'm new to python's multiprocessing package, and my confusion will probably be easy for those who know more to clear things up. I read about concurrency and searched for other questions like this and found nothing. (FYI I do not want to use multithreading because GIL will slow down my application very much.)
I think in the context of events. I want to start several processes, waiting for an event. If an event occurs, it is assigned to a specific process that is running, and then returns to the idle state. There may be a better way to do this, but my reasoning is that I should spawn all processes once and keep them open indefinitely, and not create and then close the process every time an event occurs. Speed ββis a problem for me, and my events can occur many thousands of times per second.
I came up with the following toy example, which is designed to send even numbers to one process and odd numbers to another. Both processes are the same, they just add a number to the list.
from multiprocessing import Process, Queue, Pipe slist=['even','odd'] Q={} Q['even'] = Queue() Q['odd'] = Queue() ev,od = [],[] Q['even'].put(ev) Q['odd'].put(od) P={} P['even'] = Pipe() P['odd'] = Pipe() def add_num(s): """ The worker function, invoked in a process. The results are placed in a list that pushed to a queue.""" # while True : if not P[s][1].recv(): print s,'- do nothing' else: d = Q[s].get() print d d.append(P[s][1].recv()) Q[s].put(d) print Q[s].get() P[s][0].send(False) print 'ya' def piper(s,n): P[s][0].send(n) for k in [S for S in slist if S != s]: P[k][0].send(False) add_num(s) procs = [ Process ( target=add_num, args=(i,) ) for i in ['even','odd']] for s in slist: P[s][0].send(False) for p in procs: p.start() p.join() for i in range(10): print i if i%2==0: s = 'even' else: s = 'odd' piper(s,i) print 'results:', Q['odd'].get(),Q['even'].get()
This code creates the following:
even - do nothing
Any understanding of the wise in this problem, where my code or argument is not suitable, etc., would be greatly appreciated.