3 个线程正在运行。
线程 1 print_waiting()
打印等待消息。
线程 2 和 3 正在等待触发器文件夹确定。如果OK存在,线程2和3将同时执行函数。他们只锁定线程1。
我正在考虑使用 threading.Lock()
。
如何只锁定线程 1 但线程 2 和 3 继续运行?我应该使用多少锁?
import os
import time
import threading
waiting = True
trigger_file = r'D:\Desktop\OK'
def sub_process():
print('1')
time.sleep(5)
print('2')
time.sleep(5)
print('3')
time.sleep(5)
print('4')
time.sleep(5)
print('5')
def print_waiting(): # animation of waiting
while(waiting):
for loading_symbol in ['|','/','-','\\','|','/','-','\\','|']:
print('\r[INFO] Waiting for trigger... '+loading_symbol,end="")
time.sleep(0.2)
def triggerListener_one(): # trigger a function if the file exist
while(True):
if os.path.exists(trigger_file):
global waiting
waiting=False
print('\n[INFO] main process start')
sub_process()
waiting=True
def triggerListener_two(): # trigger a function if the file exist
while(True):
if os.path.exists(trigger_file):
global waiting
waiting=False
print('\n[INFO] main process start')
sub_process()
waiting=True
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_waiting)
t2 = threading.Thread(target=triggerListener_one)
t3 = threading.Thread(target=triggerListener_two)
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# starting thread 3
t3.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# wait until thread 2 is completely executed
t3.join()
# both threads completely executed
print("Done!")