部分コード:第1のプロセスがまだ稼動している間に終了した第2のプロセスにどのように参加できますか?
p1 = Process(target1, args1)
p2 = Process(target2, args2)
p1.start()
p2.start()
p1.join()
p2.join()
任意のプロセスが中断されるかもしれないことを良いチャンスがあります。したがって、私は結合がブロッキングコールであるため、順調に結合してはいけません。
助けてください。
部分コード:第1のプロセスがまだ稼動している間に終了した第2のプロセスにどのように参加できますか?
p1 = Process(target1, args1)
p2 = Process(target2, args2)
p1.start()
p2.start()
p1.join()
p2.join()
任意のプロセスが中断されるかもしれないことを良いチャンスがあります。したがって、私は結合がブロッキングコールであるため、順調に結合してはいけません。
助けてください。
あなたの意図によりますが、Process.join()
は、選択したプロセスが完了するのを待っている(メインプロセスに戻ってくる)ために使用しますが、 1つが完了するのを待ってから、2つ目が終了します。
multiprocessing.Event
を使用してプロセスに渡すことをお勧めします。プロセスが終了するとフラグが設定され、メインプロセスでイベントループが発生し、プロセスが終了したことを確認できます。同じシステムを使用して、プロセスの終了を指示することもできます。
あなたはできるもProcess.join()
へtimeout
セットでお使いのプロセスをループしたいすべてのは、何かのように、プロセスは、前工程で待たずに終了したときに特定することである場合:
import multiprocessing
import time
def target(name, timeout=5):
print("{} started...".format(name))
time.sleep(timeout)
print("{} finishing...".format(name))
# define a process list for convenience with initialization/shutdown:
processes = {
"P1": {"target": target, "args": ["P1", 5]},
"P2": {"target": target, "args": ["P2", 3]},
"P3": {"target": target, "args": ["P3", 8]},
"P4": {"target": target, "args": ["P4", 1]},
}
if __name__ == "__main__": # cross-platform multiprocessing guard
# initialize and start our processes:
for name, kwargs in processes.items(): # loop through the process list
print("Initializing: {}...".format(name))
processes[name] = multiprocessing.Process(**kwargs)
print("Starting: {}...".format(name))
processes[name].start()
# when its time to exit...
processes = processes.items() # easier to manage as a list of tuples
while processes: # loop for as long as we have alive processes...
name, process = processes.pop(0) # remove the first element from our process list
process.join(0.1) # trying to join the current process, wait for 100ms
if process.is_alive(): # Process still alive, moving to the next one...
processes.append((name, process)) # add it to the back of the queue
else:
print("{} ended!".format(name))
print("Woo-hoo! All processes exited...")
注:これは動作しますこの場合、サブプロセスをメインプロセスに「参加」せずに、サブプロセスがjoin(本質的にはwait()
)を呼び出さずにタスクを待っても、それは決して閉じることはありません。しかし、もう一度、最初のケースでmultiprocessing.Event
を使いたいのです。