3
我在網上發現了這個代碼,預測的結果應該顯示當前正在處理的進程名稱,但是當我運行代碼時,它只給出結果而不是名稱。我運行Windows 7 Python 2.7.3。Python多處理並不像預測的那樣工作
代碼:
import multiprocessing
def do_calculation(data):
return data * 2
def start_process():
print 'Starting', multiprocessing.current_process().name
if __name__ == '__main__':
inputs = list(range(10))
print 'Input :', inputs
builtin_outputs = map(do_calculation, inputs)
print 'Built-in:', builtin_outputs
pool_size = multiprocessing.cpu_count() * 2
pool = multiprocessing.Pool(processes=pool_size,
initializer=start_process,
)
pool_outputs = pool.map(do_calculation, inputs)
pool.close() # no more tasks
pool.join() # wrap up current tasks
print 'Pool :', pool_outputs
預期結果:
$ python multiprocessing_pool.py
Input : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Built-in: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Starting PoolWorker-11
Starting PoolWorker-12
Starting PoolWorker-13
Starting PoolWorker-14
Starting PoolWorker-15
Starting PoolWorker-16
Starting PoolWorker-1
Starting PoolWorker-2
Starting PoolWorker-3
Starting PoolWorker-4
Starting PoolWorker-5
Starting PoolWorker-8
Starting PoolWorker-9
Starting PoolWorker-6
Starting PoolWorker-10
Starting PoolWorker-7
Pool : [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
你爲什麼期待這種情況發生?你粘貼的輸出看起來像你顯示的代碼的正確行爲。 – Gian
我唯一的猜測是你實際上希望你的'do_calculation'主體看起來像這樣:'return(data * 2,multiprocessing.current_process()。name)'它返回'data * 2'和工作者名字一個元組。 – sberry
你試過檢查multiprocessing.cpu_count()返回什麼嗎? – fsw