sem.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2. ### Семафоры и барьеры
  3. from threading import Thread, BoundedSemaphore, current_thread, Barrier
  4. import time
  5. import random
  6. max_connections = 5
  7. pool = BoundedSemaphore(value=max_connections)
  8. def test():
  9. with pool:
  10. slp = random.randint(1, 5)
  11. print(f"{current_thread().name} - sleep ({slp})")
  12. time.sleep(slp)
  13. # for i in range(10):
  14. # Thread(target=test, name=f'Thr-{i}').start()
  15. ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  16. ### Барьеры
  17. def test_barrier(barrier):
  18. slp = random.randint(3, 7)
  19. time.sleep(slp)
  20. print(f"Поток [{current_thread().name}] запущен в ({time.ctime()})")
  21. barrier.wait()
  22. print(f"Поток [{current_thread().name}] преодолел барьер в ({time.ctime()})")
  23. bar = Barrier(5)
  24. for i in range(5):
  25. Thread(target=test_barrier, args=(bar, ), name=f"Thread-{i}").start()