Python多处理进程ID

时间:2018-05-04 10:57:30

标签: python python-multiprocessing python-pool

我正在使用多处理.Pool也运行不同的进程(例如4个进程),我需要对每个进程进行ID,这样我就可以在每个进程中执行不同的操作。

由于我在一个while循环中运行了池,对于第一次迭代,我可以知道每个进程的ID,但是对于第二次和更多次迭代,这个ID发生了变化,或者至少我找不到一个似乎是对于所有迭代中的每个进程都是相同的。

代码的相关部分如下:

     while i <= maxiter:
        print('\n' + 'Iteration: %r'%i + '\n')

        pool = mp.Pool(processes = numprocs)

        swarm = pool.map_async(partial(proxy, costf = costFunc, i=i),Swarm)
        pool.close()
        pool.join()

        Swarm = swarm.get()

我尝试使用以下属性来正确识别进程,但它对我不起作用:

print(mp.Process().name)
print(mp.current_process().name)

这样输出是:

Iteration: 1

Process-2:1
Process-1:1
ForkPoolWorker-1
ForkPoolWorker-2
Process-3:1
ForkPoolWorker-3
Process-2:2
ForkPoolWorker-2
Process-3:2
Process-2:3
ForkPoolWorker-3
ForkPoolWorker-2
Process-1:2
ForkPoolWorker-1
Process-4:1
Process-3:3
ForkPoolWorker-4
ForkPoolWorker-3
Process-2:4
ForkPoolWorker-2

Iteration: 2

Process-5:1
ForkPoolWorker-5
Process-5:2
Process-7:1
ForkPoolWorker-7
Process-6:1
ForkPoolWorker-5
ForkPoolWorker-6
Process-5:3
ForkPoolWorker-5
Process-7:2
ForkPoolWorker-7
Process-5:4
ForkPoolWorker-5
Process-6:2
ForkPoolWorker-6
Process-7:3
ForkPoolWorker-7
Process-8:1
ForkPoolWorker-8

任何想法如何每次都以相同的方式对每个进程进行ID?

编辑1:

我已将程序简化为此,但想法是一样的:

import random, numpy as np,time
import multiprocessing as mp

def costFunc(i):
    print(mp.current_process().name,mp.Process().name)
    return i*1

class PSO():
    def __init__(self,maxiter,numprocs):

        # Begin optimization Loop
        i = 1
        self.Evol = []

        while i <= maxiter:
            print('\n' + 'Iteration: %r'%i + '\n')
            pool = mp.Pool(processes = numprocs)
            swarm = pool.map_async(costFunc,(i,))
            pool.close()
            pool.join()

            Swarm = swarm.get()

            i += 1

if __name__ == "__main__":
    #mp.set_start_method('spawn')
    PSO(10,1)

输出:

Iteration: 1
ForkPoolWorker-1 Process-1:1
Iteration: 2
ForkPoolWorker-2 Process-2:1
Iteration: 3
ForkPoolWorker-3 Process-3:1
Iteration: 4
ForkPoolWorker-4 Process-4:1
Iteration: 5
ForkPoolWorker-5 Process-5:1
Iteration: 6
ForkPoolWorker-6 Process-6:1
Iteration: 7
ForkPoolWorker-7 Process-7:1
Iteration: 8
ForkPoolWorker-8 Process-8:1
Iteration: 9
ForkPoolWorker-9 Process-9:1
Iteration: 10
ForkPoolWorker-10 Process-10:1

1 个答案:

答案 0 :(得分:2)

您正在循环的每次迭代中创建一个新池,因此池中的进程永远不会被重用。

pool = mp.Pool(processes = numprocs)(以及pool.close()pool.join())移出while循环以重新使用池中的进程。