Untitled
unknown
plain_text
a year ago
1.0 kB
3
Indexable
import threading import time class AsyncSemaphore(object): def __init__(self, value=1): self._value = value self._condition = threading.Condition() def acquire(self): with self._condition: while self._value <= 0: self._condition.wait() self._value -= 1 def release(self): with self._condition: self._value += 1 self._condition.notify() def worker(semaphore_value, task_id): semaphore_value.acquire() print("Task {} acquired the semaphore".format(task_id)) time.sleep(2) semaphore_value.release() print("Task {} released the semaphore".format(task_id)) def main(): semaphore = AsyncSemaphore(value=20) threads = [] for i in range(1000): t = threading.Thread(target=worker, args=(semaphore, i)) t.start() threads.append(t) for t in threads: t.join() if __name__ == "__main__": main()
Editor is loading...
Leave a Comment