4

以下のコードは Unix では完全に動作しますが、Windows 7 では multiprocessing.TimeoutError を生成します (どちらの OS も python 2.7 を使用します)。

理由はありますか?ありがとう。

from multiprocessing import Pool

def increment(x):
    return x + 1

def decrement(x):
    return x - 1

pool = Pool(processes=2)
res1 = pool.map_async(increment, range(10))
res2 = pool.map_async(decrement, range(10))

print res1.get(timeout=1)
print res2.get(timeout=1)
4

1 に答える 1

1

if __name__ == '__main__':実際のプログラム ロジックをブロックの横に配置する必要があります。

Unixy システムでは、Python がフォークして、作業する複数のプロセスを生成します。Windows にはフォークがありません。Python は新しいインタープリターを起動し、代わりにすべてのモジュールを再インポートする必要があります。これは、各サブプロセスがメイン モジュールを再インポートすることを意味します。作成したコードの場合、モジュールを再インポートすると、新しく起動された各プロセスが独自のプロセスを起動します。

参照: http://docs.python.org/library/multiprocessing.html#windows

編集これは私のために働く:

from multiprocessing import Pool

def increment(x):
    return x + 1

def decrement(x):
    return x - 1

if __name__ == '__main__':
    pool = Pool(processes=2)
    res1 = pool.map_async(increment, range(10))
    res2 = pool.map_async(decrement, range(10))

    print res1.get(timeout=1)
    print res2.get(timeout=1)
于 2012-09-17T18:47:09.460 に答える