2017-02-11 15 views
0

この質問は、コミュニティ管理のバックポートconcurrent.futuresを使用して、Python 2固有の質問です。並行未処理の処理プールにタスクをサブミットして送信します

私は2つのタスクを並列に実行するためにProcessPoolExecutorを使用しています(maxWorkersを2に設定)。これらのタスクはどちらもPythonの関数であり、私はそれらのそれぞれが独自のプロセスで動作するようにしたいと思います。彼らはお互いに調整する必要はありません(私は終了ステータスを知る必要はありません)。私はちょうど同時にプロセスを起動し、同時に実行されるプロセスの数を制限したいと考えています。

import concurrent.futures as futures 
import time 


def do_stuff(name): 
    for x in range(10): 
     print name, x 
     time.sleep(1) 


pool = futures.ProcessPoolExecutor(max_workers=2) 
pool.submit(do_stuff("a")) 
print "a submitted!" 
pool.submit(do_stuff("b")) 

これは、しかし、プリント

a 0 a 1 ... a 9 a submitted! b 0 b 1 ... b 9

なぜsubmitブロッキング操作はありますか?ノンブロッキングの同等品はありますか?

ここでは、私が必要とする動作を持つmultiprocessingライブラリを使用した例を示します。ノンブロッキングで各プロセスを起動し、join(おそらくwaitpid(2)のまわりの薄いラッパー)を呼び出します。しかし、この手法では、ある瞬間に並行して実行されるプロセスの数を制限することはできません。あなたのコードから

import multiprocessing 
import time 


def do_stuff(name): 
    for x in range(10): 
     print name, x 
     time.sleep(1) 


proc_a = multiprocessing.Process(target=do_stuff, args="a") 
proc_b = multiprocessing.Process(target=do_stuff, args="b") 
proc_a.start() 
proc_b.start() 
proc_a.join() 
proc_b.join() 
+0

pool.submit(do_stuff( "a"))ここでdo_stuff( "a")のため実際にdo_stuffメソッドを実行しています。 – minhajul

答えて

4

(代わりに同時1の)シリアルプリントアウトは、あなたがあなたの関数の引数を提出するために使用していた間違った構文に起因すると思われます。引数は、Executor.submit()のカンマを使用して関数と区切る必要があります。代わりにこのバージョンをお試しください。

import concurrent.futures as futures 
import time 

def do_stuff(name): 
    for x in range(10): 
     print name, x 
     time.sleep(1) 

pool = futures.ProcessPoolExecutor(max_workers=2) 
pool.submit(do_stuff, "a") 
print "a submitted!" 
pool.submit(do_stuff, "b") 
print "b submitted!" 

はまた、私はそれが適切な閉鎖/ concurrent.futures.Executorのシャットダウンを確保するよう可能な限りあなたの投稿を管理するために「と」ステートメントを使用することをお勧めします。これは文書で言及されています。

with futures.ProcessPoolExecutor(max_workers=2) as executor: 
    executor.submit(do_stuff, "a") 
    print "a submitted!" 
    executor.submit(do_stuff, "b") 
    print "b submitted!" 
関連する問題