multithreading - Python multiprocessing/threading with shared variables that only will be read -


Considering the code given below, I would like to run 3 experiments at once, the experiments are free, only one The thing they share is a model object, which they read only.

Since there is no difficulty in threading this, how can I do this in Python? I want to use a pool or to make sure that only three experiments run at one time. Will I use multi-processing? If so, how short and shortest?

  #! / Usr / bin / env python2.6 Import time range Model: name = "" def __init __ (self, name): selfname.name = name class experiment: id = 0 model = none did = wrong def __init __ ( Self, id, model): self.id = id self.model = Model DEF def (self): _ (060) for category: print "% s experiment% d"% (self.model.name, Id) time.sleep (1) self.done = true if __name__ == "__main__": experiments = [] model = model ("in the number (0,5): (experiment (i, model)) for experiments  

Check docs to run 3 experiments in the same time, special From the form:

There are so many examples that you should get on your way. For example, I can come up with:

/ Code / # / / bin / bin / python2.6 Import time import multiplexing class Model: name = "" def __init __ (auto, name): selfname.name = name def run_experiment (id, model): print "experiment% d "% Id" for range (0, 60) is starting: print "is% s experiment% d"% (model.name, id) from% _ "result for% id" __name__ == "__main__": model = model ("statistical model") experiments = ((i, model) (0, 5)) In the category (= 0, 5) pool = multiprocessing. Poll (3) Results = [for use experiment.apple_async (run_desk, experiment) for results: r = result.get () # R # or nothing, I think ... < What do docs say about using the multiprocessing module:

The functionality within this package is required by the th children The method can be imported by the __ main___ This programming is included in the guidelines, however it It is worth noting here. This means that some examples, such as multiprocessing.Pool , will not work in interactive interpreter


Comments