123456789101112131415161718192021222324252627282930313233343536 |
- ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ### Семафоры и барьеры
- from threading import Thread, BoundedSemaphore, current_thread, Barrier
- import time
- import random
- max_connections = 5
- pool = BoundedSemaphore(value=max_connections)
- def test():
- with pool:
- slp = random.randint(1, 5)
- print(f"{current_thread().name} - sleep ({slp})")
- time.sleep(slp)
- # for i in range(10):
- # Thread(target=test, name=f'Thr-{i}').start()
- ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- ### Барьеры
- def test_barrier(barrier):
- slp = random.randint(3, 7)
- time.sleep(slp)
- print(f"Поток [{current_thread().name}] запущен в ({time.ctime()})")
-
- barrier.wait()
- print(f"Поток [{current_thread().name}] преодолел барьер в ({time.ctime()})")
- bar = Barrier(5)
- for i in range(5):
- Thread(target=test_barrier, args=(bar, ), name=f"Thread-{i}").start()
|