Skip to content

Instantly share code, notes, and snippets.

@vishesh
Last active December 22, 2015 09:58
Show Gist options
  • Select an option

  • Save vishesh/6455452 to your computer and use it in GitHub Desktop.

Select an option

Save vishesh/6455452 to your computer and use it in GitHub Desktop.
Python synchronization helpers.
import threading
def threadify(func):
"A decorator to run a function asynchronously"
def run(*fargs, **fkwargs):
threading.Thread(target=func, args=fargs, kwargs=fkwargs).start()
return run
class Barrier:
"Synchronization barrier"
def __init__(self, numthreads):
self.lock = threading.Lock()
self.numthreads = numthreads
self.sem = threading.Semaphore(0)
self.sem2 = threading.Semaphore(self.numthreads)
self.count = 0
def sync(self):
self.sem2.acquire()
with self.lock:
self.count += 1
if self.count == self.numthreads:
self.sem.release()
self.sem.acquire()
with self.lock:
self.count -= 1
if self.count != 0:
self.sem.release()
else:
for x in range(self.numthreads):
self.sem2.release()
class Semaphore2:
"Semaphore that takes negative init value and can release value > 1"
def __init__(self, value):
self.value = value
self.sem = threading.Semaphore(value if value >= 0 else 0)
self.lock = threading.Lock()
def acquire(self):
self.sem.acquire()
def release(self, value=1):
with self.lock:
if self.value < 0:
self.value += value
if self.value >= 0:
for i in range(value):
self.sem.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment