How to use classes with Python multiprocessing?

后端 未结 2 957

Here\'s some sample code that is reads a file and adds up each line. It is supposed to add up all the numbers from 0-20. However, I always get a result of 0.

<
2条回答
  •  无人及你
    2021-01-27 02:40

    Each subprocess calling f updates its own copy of total and therefore main process's total is not affected.

    You can have each subprocess return the result of its computation (in your mock example, that's just the input, unchanged), and then accumulate it in the main process. E.g.:

    def f(input):
      return input
    
    results = pool.map(f, mock_file)
    for res in results:
      total.add(res)
    

提交回复
热议问题