我有一个运行蒙特卡罗模拟的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
版本的localhost:8087
会有效,但事实并非如此。
答案 0 :(得分:2)
正常的全局变量不会在进程之间以线程之间共享的方式共享。您需要使用过程感知数据结构。对于您的用例,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
传递给了孩子,以使代码与Windows兼容,而Windows无法在父母和子女之间共享读/写全局变量。if __name__ == "__main__":
后卫,再次帮助Windows兼容性,这只是一般的最佳做法。