multiprocessing.pool.map()によって呼び出される関数で番号を順番にインクリメントしようとしています。次のコードを実行すると、各番号のプールと同じ回数だけ番号がインクリメントされます。
import time
import multiprocessing
import decimal
import random
lists = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h','i', 'j', 'k']
def thefunction(listi):
global number
number += 1
time.sleep(decimal.Decimal(random.random()))
print time.strftime('%H:%M:%S'), number, listi
number = 0
pool = multiprocessing.Pool(4)
pool.map(thefunction, lists)
print number
結果は次のように出力されます
01:01:28 1 b
01:01:28 2 e
01:01:28 1 a
01:01:28 1 c
01:01:28 1 d
01:01:28 2 h
01:01:29 2 i
01:01:29 2 g
01:01:29 3 f
01:01:29 3 j
01:01:29 3 k
0
どうすれば正しく番号を増やすことができますか?
(time.sleep(decimal.Decimal(random.random()))は、同じ行へのスクリプトの印刷を停止するためにのみ追加されました)