Python には Java の CountDownLatch と同様の制御メカニズムがありますか? 質問する

Python には Java の CountDownLatch と同様の制御メカニズムがありますか? 質問する

まず、これは宿題の問題だということを言っておきます。教授から課題が出され、1 回は Java で、もう 1 回は別の言語で記述する必要がありました。2 番目の言語として、少なくとも少しは慣れている Python を選択しました。プログラムは次のように動作する必要があります。

start the main method/thread, which we will call parent
start thread child 1 from the parent
start thread grandchild from thread child 1
start thread child 2 from the parent
print grandchild from the grandchild thread
print child 2 from the child 2 thread
print child 1 from the child 1 thread
print parent from the main method/parent thread

これらのことは、この順序で実行する必要があります。これらのことが起こる方法を整理するために、CountDownLatch を使用して Java でこれを行うコードを作成しました。ただし、Python で同様のメカニズムは見つかりませんでした (私は Java ほど Python に詳しくありませんが)。名前がわからないために見つけられないだけの、同様のメカニズムがあるのでしょうか?

ベストアンサー1

次のようにthreading.Conditionを使用してCountDownLatchを実装できます。

import threading

class CountDownLatch(object):
    def __init__(self, count=1):
        self.count = count
        self.lock = threading.Condition()

    def count_down(self):
        self.lock.acquire()
        self.count -= 1
        if self.count <= 0:
            self.lock.notifyAll()
        self.lock.release()

    def await(self):
        self.lock.acquire()
        while self.count > 0:
            self.lock.wait()
        self.lock.release()

おすすめ記事