這可能是最簡單直接創建mp.Process
ES(不含mp.Pool
):
import multiprocessing as mp
import time
class Connection(object):
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def work(inqueue,conn):
name=mp.current_process().name
while 1:
data=inqueue.get()
time.sleep(.5)
print('{n}: work done with connection {c} on data {d}'.format(
n=name,c=conn,d=data))
inqueue.task_done()
if __name__ == '__main__':
N=4
procs=[]
inqueue=mp.JoinableQueue()
for i in range(N):
conn=Connection(name='Conn-'+str(i))
proc=mp.Process(target=work,name='Proc-'+str(i),args=(inqueue,conn))
proc.daemon=True
proc.start()
datas = range(1,11)
for data in datas:
inqueue.put(data)
inqueue.join()
產生
Proc-0: work done with connection Conn-0 on data 1
Proc-1: work done with connection Conn-1 on data 2
Proc-3: work done with connection Conn-3 on data 3
Proc-2: work done with connection Conn-2 on data 4
Proc-0: work done with connection Conn-0 on data 5
Proc-1: work done with connection Conn-1 on data 6
Proc-3: work done with connection Conn-3 on data 7
Proc-2: work done with connection Conn-2 on data 8
Proc-0: work done with connection Conn-0 on data 9
Proc-1: work done with connection Conn-1 on data 10
注意Proc
每次對應的編號相同Conn
。
謝謝,這是關鍵。 – 2011-03-18 19:00:53
你能標記它作爲答案嗎? – 2011-03-18 19:39:11