首页 > 解决方案 > 如何锁定主线程?

问题描述

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!")

标签: pythonmultithreading

解决方案


推荐阅读