I have a python program that runs a Monte Carlo simulation to find answers to probability questions. I am using multiprocessing and here it is in pseudo code
import multiprocessing
def runmycode(result_queue):
print "Requested..."
while 1==1:
iterations +=1
if "result found (for example)":
result_queue.put("result!")
print "Done"
processs = []
result_queue = multiprocessing.Queue()
for n in range(4): # start 4 processes
process = multiprocessing.Process(target=runmycode, args=[result_queue])
process.start()
processs.append(process)
print "Waiting for result..."
result = result_queue.get() # wait
for process in processs: # then kill them all off
process.terminate()
print "Got result:", result
I'd like to extend this so that I can keep a unified count of the number of iterations that have been run. Like if thread 1 has run 100 times and thread 2 has run 100 times then I want to show 200 iterations total, as a print to the console. I am referring to the iterations
variable in the thread process. How can I make sure that ALL threads are adding to the same variable? I thought that using a Global
version of iterations
would work but it does not.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…