TelenkovDmitry 1 year ago
parent
commit
fbdf704d07
1 changed files with 82 additions and 1 deletions
  1. 82 1
      courses/python_threading/les_1.py

+ 82 - 1
courses/python_threading/les_1.py

@@ -47,7 +47,88 @@ def thread_test_2():
     print("finish")
 
 
-thread_test_2()
+# thread_test_2()
+
+### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+### Синхронизация потоков. Блокировка отоков.z
+
+# value = 0
+# locker = threading.Lock() # locker может использовать любой поток
+# rlocker = threading.RLock() # может разблокировать только тот поток, который вызвал блокировку
+
+
+def inc_value():
+    global value
+    while True:
+        locker.acquire()
+        value += 1
+        print(value)
+        time.sleep(1)
+        locker.release()
+
+def inc_value_with():
+    global value
+    while True:
+        with locker:
+            value += 1
+            print(value)
+            time.sleep(0.1)
+            locker.release()
+
+
+# for _ in range(5):
+#     threading.Thread(target=inc_value).start()
+
+
+### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+### Таймеры
+
+def timer_output():
+    while True:
+        print("test")
+        time.sleep(1)
+
+def timer_start():
+    thr = threading.Timer(5, timer_output)
+    thr.daemon = True # Поток будет завершен после завершения основого потока
+    thr.start()
+
+    # thr.cancel()    # отменить поток
+
+
+    while True:
+        print("main")
+        time.sleep(1)
+
+# timer_start()    
+
+
+### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+### local Хранение данных и атрибуты
+
+data = threading.local()
+
+def get_data():
+    print(data.value)
+
+def data_thread_1():
+    data.value = 111
+    get_data()
+    print("t1:", data.value)
+
+def data_thread_2():
+    data.value = 222
+    get_data()
+    print("t2:", data.value)
+
+def start_data_threads():
+    threading.Thread(target=data_thread_1).start()
+    threading.Thread(target=data_thread_2).start()
+
+start_data_threads()
+
+
+