在多处理过程中保持统一计数?

2024-10-01 19:15:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python程序,运行montecarlo模拟来寻找概率问题的答案。我使用多重处理,这里是伪代码

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可以工作,但是不行。在


Tags: in程序forqueueresult概率线程multiprocessing
1条回答
网友
1楼 · 发布于 2024-10-01 19:15:28

正常的全局变量在进程之间的共享方式与线程之间的共享方式不同。您需要使用过程感知的数据结构。对于您的用例,^{}应该可以正常工作:

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))

一些注意事项:

  1. 我显式地将Value传递给子代,以保持代码与Windows兼容,Windows不能在父级和子级之间共享读/写全局变量。在
  2. 我用锁保护增量,因为它不是原子操作,而且容易受到竞争条件的影响。在
  3. 我添加了一个if __name__ == "__main__":保护,同样是为了帮助与Windows兼容,并且作为一个通用的最佳实践。在

相关问题 更多 >

    热门问题