multithreading - python parallel calculations in a while loop -
i have been looking around time, haven't had luck finding example solve problem. have added example code. 1 can notice slow , 2 functions done separately.
my aim print every second latest parameter values. @ same time slow processes can calculated in background. latest value shown , when process ready value updated.
can recommend better way it? example helpful.
thanks lot.
import time def processa(para): # imitate slow process time.sleep(5) para += 2 return para def processb(parb): # imitate slow process time.sleep(10) parb += 5 return parb # start here i, para, parb = 1, 0, 0 while true: # endless loop print(i) print(para) print(parb) time.sleep(1) += 1 # update parameter para = processa(para) # update parameter b parb = processb(parb)
i imagine should you. has benefit of being able add parallel funcitons total equal number of cores have. edits welcome.
#import time module import time #import appropriate multiprocessing functions multiprocessing import pool #define functions #whatever slow function def slowfunction(x): return somefunction(x) #printingfunction def printingfunction(new,current,timedelay): while new == current: print current time.sleep(timedelay) #set initial value printed. #depending on function may take time. currentvalue = slowfunction(sometemporallydynamicvairable) #establish pool pool = pool() while true: #endless loop #an asynchronous function, continue # run in background while printing operates. newvalue = pool.apply_async(slowfunction(sometemporallydynamicvairable)) pool.apply(printingfunction(newvalue,currentvalue,1)) currentvalue = newvalue #close pool pool.close()
Comments
Post a Comment