barrier.py 1005 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. '''This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. See COPYING.lesser and README.md in the root of this project for full details'''
  4. from threading import *
  5. #Barrier implementation from here
  6. #From http://greenteapress.com/semaphores/index.html
  7. class barrier:
  8. def __init__(self, n):
  9. self.n = n
  10. self.count = 0
  11. self.mutex = Semaphore(1)
  12. self.turnstile = Semaphore(0)
  13. self.turnstile2 = Semaphore(0)
  14. def phase1(self):
  15. self.mutex.acquire()
  16. self.count += 1
  17. if self.count == self.n:
  18. for i in range(self.n):
  19. self.turnstile.release()
  20. self.mutex.release()
  21. self.turnstile.acquire()
  22. def phase2(self):
  23. self.mutex.acquire()
  24. self.count -= 1
  25. if self.count == 0:
  26. for i in range(self.n):
  27. self.turnstile2.release()
  28. self.mutex.release()
  29. self.turnstile2.acquire()
  30. def wait(self):
  31. self.phase1()
  32. self.phase2()