python - 如何锁定主线程?
问题描述
3个线程正在运行。
线程 1 print_waiting()
打印等待消息。
线程 2 & 3正在等待触发文件夹OK。如果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!")
解决方案
推荐阅读
- java - Android 通知 - 用另一个通知替换一个通知
- gensim - 为海量数据集加速 Gensim 的 Word2vec
- uml - 在 UML 中,如何调用为其构建状态图的对象?
- angular - 根据所选选项显示字段 - 反应式表单
- css - 使文本随背景更改为新颜色,例如视差背景
- html - HTML 在 div 标签中包含没有额外空格的文本
- jax-rs - 如何在 JAX-RS ContainerRequestFilter 中获取路径模板?
- c++ - 在 VS2019 项目中集成 ImageMagick:x64-windows-static 库
- mongodb - 如何在微服务架构中将默认数据播种到 Mongo db(或任何数据库)?
- javascript - Xpath 函数在 playwright 中不起作用