20

So, I will start by saying that this is for a homework problem. My professor gave us an assignment which must be written once in Java and once in another language; I chose the second language to be Python since I'm at least a little familiar with it. The program must work in the following way:

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

These things must be done in this order. I have written code that does this in Java using CountDownLatch in order to organize the way these things occur. However, I didn't see a similar mechanism in Python (although I'm less familiar with Python than Java). Is there a similar mechanism that maybe I just can't find because I don't know what it's called?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Gossamer Shadow
  • 387
  • 1
  • 5
  • 16

3 Answers3

27

you can implement CountDownLatch using threading.Condition like this:

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()
kk17
  • 601
  • 6
  • 14
1

Look at the Semaphore or Condition classes from the threading module.

Roland Smith
  • 42,427
  • 3
  • 64
  • 94
0

Python 3.2 added a Barrier class that has some overlapping functionality with a CountDownLatch. The main differences are it can be reset, and there isn't a way to count down without waiting.

https://docs.python.org/3/library/threading.html#barrier-objects

David Ehrmann
  • 7,366
  • 2
  • 31
  • 40