我有一个运行蒙特卡罗模拟的python程序,以找到概率问题的答案。我正在使用多重处理,这是伪代码
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
我想扩展此范围,以便可以对已运行的迭代次数进行统一计数。就像线程1运行了100次,线程2运行了100次一样,我想显示总共200次迭代,作为控制台打印。我指的iterations是线程过程中的变量。如何确保所有线程都添加到同一变量?我认为使用的Global版本iterations会行得通,但行不通。
iterations
Global
普通全局变量不像线程之间共享那样在进程之间共享。您需要使用流程感知的数据结构。对于您的用例,amultiprocessing.Value应该可以正常工作:
multiprocessing.Value
import multiprocessing def runmycode(result_queue, iterations): print("Requested...") while 1==1: # This is an infinite loop, so I assume you want something else here with iterations.get_lock(): # Need a lock because incrementing isn't atomic iterations.value += 1 if "result found (for example)": result_queue.put("result!") print("Done") if __name__ == "__main__": processs = [] result_queue = multiprocessing.Queue() iterations = multiprocessing.Value('i', 0) for n in range(4): # start 4 processes process = multiprocessing.Process(target=runmycode, args=(result_queue, iterations)) 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: {}".format(result)) print("Total iterations {}".format(iterations.value))
一些注意事项:
Value
if __name__ == "__main__":