4

現在、いくつかのサブプロセス (複数のサブプロセス) {p1、p2、p3、p4} を並行して実行しています。

いずれかが終了するまで wait() したいと思います。

私は現在、おそらく非常に非効率的なwhileループでポーリングしています

proc = [p1, p2, p3, p4]
while True:
  for p in proc:
    if p.poll() != None:
      #Do whatever

すべてのサブプロセスをポーリングするのを待つのではなく、最速の終了サブプロセスを待つ方法はありますか?

4

1 に答える 1

1

Windows を使用していない限り、これを使用できますos.wait()。最初の子プロセスが終了するまで待機するように正確に設計されています。

ただし、隠れた副作用として、プロセスの終了コードが失われることがあります (現在は 0 と見なされます)。自分で設定することは可能ですが、ハックです。

proc = [p1, p2, p3, p4]
pid, status = os.wait()
for p in proc:
    if p.pid == pid:
        # We need to set the process's exit status now, or we
        # won't be able to retrieve it later and it will be
        # assumed to be 0.
        # This is a kind of hacky solution, but this function has existed
        # ever since subprocess was first included in the stdlib and is
        # still there in 3.10+, so it *should* be pretty stable.
        p._handle_exitstatus(status)

        #Do whatever

注:これはすべてpython 3でも同様に機能します

于 2021-03-31T08:16:01.187 に答える