# multiprocessing.py # illustration of multiple processes # -*- coding: utf-8 -*- # diese Zeile legt die Codierung von Umlauten fest ################################################################## import sys, time, numpy as np #--> import multiprocessing as mp # <-- def worker(id, input, Q): '''a simple worker process Args: * int id identification number * float input input * mp.Queue multiprocessing Queue ''' print ('worker %i started'%id, time.strftime('%y/%m/%d-%H:%M:%S') ) # code to be executed on worker here --> result = calcF(input) # send result to main process Q.put( (id, result) ) print ('worker %i finished'%id, time.strftime('%y/%m/%d-%H:%M:%S') ) return # def calcF(input): '''MC-calculation of volume of a high-dimensional sphere with radius 1 Args: * float input seed for random generator ''' d, npoints = 16, 1000000 # dimension of sphere & number of sampling points print(' volume fraction of %i-dimenional sphere and cube'%(d)) i, inside = 0, 0. np.random.seed(np.int64(1000000*input) ) # seed random generator while i <= npoints: # test if vector of d random coordinates in [-1,1] is inside sphere if np.sum( (1.-2*np.random.random(d))**2 ) <= 1.: inside += 1 i += 1 Vratio = inside / npoints err = np.sqrt(Vratio * (1. - Vratio) / npoints) return Vratio, err # important: # this line protects rest of the script from being executed in sub-processes if __name__ == "__main__": # - - - - - - - - - - - - - - - - - - - - - - - - - if len(sys.argv) < 2: nworkers = 4 else: nworkers = int(sys.argv[1]) # set up a Queue for data transfer (results from workers) Q = mp.Queue(nworkers) # define and start worker processes input = np.random.rand(nworkers) procs=[] for i in range(nworkers): name='worker %i'%(i) prc = mp.Process(name=name, target = worker, args=(i, input[i], Q ) ) procs.append(prc) #store in process list prc.start() print(' -> starting process ', prc.name, ', PID=', prc.pid) # wait for processes to finish for prc in procs: prc.join() # collect results results = [] print("\nresults from workers:") while Q.qsize(): id, r = Q.get() print(' #%i: %.3g +/- %.2g'%(id, r[0],r[1]) )