Skip to content

Instantly share code, notes, and snippets.

@itolosa
Last active September 27, 2015 08:57
Show Gist options
  • Save itolosa/906a2eac98de4d4dad19 to your computer and use it in GitHub Desktop.
Save itolosa/906a2eac98de4d4dad19 to your computer and use it in GitHub Desktop.
proto semaphore
import threading
mutex1 = threading.Lock()
sem_limit = 5
sem_count = sem_limit
lista1 = []
def acquire_sem():
mutex1.acquire()
if sem_count == 0:
current_thread = threading.current_thread()
lista1.append(current_thread)
mutex1.release()
current_thread.sleep()
else:
sem_count -= 1
mutex1.release()
def release_sem():
mutex1.acquire()
if sem_count < sem_limit:
ll1 = len(lista1)
i = 0
while True:
t = lista1[i]
if t.is_sleep():
t.wake_up()
lista1.remove(i)
break
i = (i+1) % ll1
sem_count += 1
mutex1.release()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment