condition.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import threading
  2. import time
  3. event = threading.Event()
  4. def test():
  5. while True:
  6. event.wait()
  7. print("test")
  8. time.sleep(2)
  9. def start_event_thread_1():
  10. event.clear()
  11. threading.Thread(target=test, daemon=True).start()
  12. time.sleep(3)
  13. event.set()
  14. while True:
  15. pass
  16. ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  17. def image_handler():
  18. thr_num = threading.current_thread().name
  19. print(f"Идет подготовка изображения из потока [{thr_num}]")
  20. event.wait()
  21. print("Изображение оправлено")
  22. def start_event_thread_2():
  23. for i in range(10):
  24. threading.Thread(target=image_handler, name=str(i)).start()
  25. print(f'Поток [{i}] запущен!')
  26. time.sleep(1)
  27. if threading.active_count() > 10:
  28. event.set()
  29. ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  30. cond = threading.Condition()
  31. def f1():
  32. while True:
  33. with cond:
  34. cond.wait()
  35. print("Получил событие!")
  36. def f2():
  37. for i in range(100):
  38. if 1 % 10 == 0:
  39. with cond:
  40. cond.notify()
  41. else:
  42. print(f"f1: {i}")
  43. time.sleep(1)
  44. threading.Thread(target=f1).start()
  45. threading.Thread(target=f2).start()