[英]Python - How can I pause at thread by other thread?
我对显示等待消息感到困惑。
对于我的程序,
第 1 步,它不断循环显示等待消息。
步骤2,如果trigger_file
存在,则停止等待消息并运行main_process()
步骤 3,完成main_process
,它再次显示等待消息。
我尝试使用变量waiting
来停止等待消息,但它不起作用我不确定如何在这种情况下使用 async/await 函数和 multithreadubg。
谢谢
import os
import time
import threading
waiting = True
trigger_file = r'D:\Desktop\OK'
def main_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(): # 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')
main_process()
waiting=True
if __name__ == "__main__":
# creating thread
t1 = threading.Thread(target=print_waiting)
t2 = threading.Thread(target=triggerListener)
# starting thread 1
t1.start()
# starting thread 2
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
预期输出:
[INFO] Waiting for trigger... -
[INFO] main process start
1
2
3
4
5
[INFO] Waiting for trigger... -
最后我用threading.Lock
来解决这个问题。 acquire
锁并在完成函数后release
锁。
class Print_waiting(threading.Thread):
def __init__(self,lock):
threading.Thread.__init__(self)
self.running = True
self.lock = lock
def run(self): # animation of waiting
while self.running:
for loading_symbol in ['|','/','-','\\','|','/','-','\\','|']:
self.lock.acquire()
print('\r[INFO] Waiting for trigger... '+loading_symbol,end="")
self.lock.release()
time.sleep(0.2)
def stop(self):
self.running = False
class TriggerListener(threading.Thread):
def __init__(self,lock):
threading.Thread.__init__(self)
self.running = True
self.lock = lock # for mutex
def run(self): # trigger a function if the file exist
while(self.running):
if os.path.exists(trigger_file):
self.lock.acquire()
print('\n[INFO] main process start')
Program.main()
self.lock.release()
def stop(self):
self.running = False
if __name__ == "__main__":
lock = threading.Lock()
waiting_anime = Print_waiting(lock)
Trigger_RPA = TriggerListener(lock)
Trigger_RPA.start()
waiting_anime.start()
Trigger_RPA.join()
waiting_anime.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.