Skip to content

Instantly share code, notes, and snippets.

@itolosa
Created September 27, 2015 09:03
Show Gist options
  • Save itolosa/f18337ba49901df3ed0f to your computer and use it in GitHub Desktop.
Save itolosa/f18337ba49901df3ed0f to your computer and use it in GitHub Desktop.
functional
import threading
class Semaphore(object):
def __init__(self, sem_limit):
self.condition1 = threading.Condition(threading.Lock())
self.sem_limit = int(sem_limit)
self.sem_count = self.sem_limit
def acquire(self):
self.condition1.acquire()
if self.sem_count == 0:
self.condition1.wait()
else:
self.sem_count -= 1
self.condition1.release()
def release(self):
self.condition1.acquire()
if self.sem_count < self.sem_limit:
self.condition1.notify()
self.sem_count += 1
self.condition1.release()
@itolosa
Copy link
Author

itolosa commented Sep 27, 2015

import threading

class Semaphore(object):
  def __init__(self, sem_limit=1):
    self.condition1 = threading.Condition(threading.Lock())
    self.sem_limit = int(sem_limit)
    self.sem_count = self.sem_limit

  def acquire(self, t=None):
    with self.condition1:
      if self.sem_count == 0:
        self.condition1.wait(timeout=t)
      else:
        self.sem_count -= 1

  def release(self, notif=1):
    with self.condition1:
      if self.sem_count < self.sem_limit:
        self.condition1.notify(n=notif)
        self.sem_count += 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment