Commits

Michael Lee  committed 4ef7c7c

Adding Python generalized barrier implementations

  • Participants
  • Parent commits a740486

Comments (0)

Files changed (2)

File concur/python/barrier_v1.py

+from __future__ import print_function
+from threading import Thread, Semaphore
+from random import random
+from time import sleep
+
+N_THREADS = 5
+count = 0
+mutex = Semaphore(1)
+turnstile = Semaphore(0)
+
+def rendezvous(tid):
+    global count
+    for i in range(100):
+        with mutex:
+            count += 1
+            if count == N_THREADS:
+                turnstile.release()
+
+        turnstile.acquire()
+        turnstile.release()
+
+        sleep(random())
+
+        with mutex:
+            if count == N_THREADS:
+                turnstile.acquire()
+            count -= 1
+
+        sleep(random()) # simulate doing something interesting
+        print('t{} completed rendezvous {}'.format(tid, i))
+
+if __name__ == '__main__':
+    for i in range(N_THREADS):
+        t = Thread(target=rendezvous, args=[i])
+        t.start()

File concur/python/barrier_v2.py

+from __future__ import print_function
+from threading import Thread, Semaphore
+from random import random
+from time import sleep
+
+N_THREADS = 5
+count = 0
+mutex = Semaphore(1)
+turnstile1 = Semaphore(0)
+turnstile2 = Semaphore(1)
+
+def rendezvous(tid):
+    global count
+    for i in range(100):
+        with mutex:
+            count += 1
+            if count == N_THREADS:
+                turnstile2.acquire()
+                turnstile1.release()
+
+        turnstile1.acquire()
+        turnstile1.release()
+
+        sleep(random()) # preempt me!
+
+        with mutex:
+            count -= 1
+            if count == 0:
+                turnstile1.acquire()
+                turnstile2.release()
+
+        turnstile2.acquire()
+        turnstile2.release()
+
+        sleep(random()) # simulate doing something interesting
+        print('t{} completed rendezvous {}'.format(tid, i))
+
+if __name__ == '__main__':
+    for i in range(N_THREADS):
+        t = Thread(target=rendezvous, args=[i])
+        t.start()