barrier.py 792 B

12345678910111213141516171819202122232425262728293031323334
  1. from threading import *
  2. #Barrier implementation from here
  3. #From http://greenteapress.com/semaphores/index.html
  4. class barrier:
  5. def __init__(self, n):
  6. self.n = n
  7. self.count = 0
  8. self.mutex = Semaphore(1)
  9. self.turnstile = Semaphore(0)
  10. self.turnstile2 = Semaphore(0)
  11. def phase1(self):
  12. self.mutex.acquire()
  13. self.count += 1
  14. if self.count == self.n:
  15. for i in range(self.n):
  16. self.turnstile.release()
  17. self.mutex.release()
  18. self.turnstile.acquire()
  19. def phase2(self):
  20. self.mutex.acquire()
  21. self.count -= 1
  22. if self.count == 0:
  23. for i in range(self.n):
  24. self.turnstile2.release()
  25. self.mutex.release()
  26. self.turnstile2.acquire()
  27. def wait(self):
  28. self.phase1()
  29. self.phase2()