Python 多线程用户提示
我有两个线程同时运行,在后台做一些事情,但是程序到达一个点,需要用户输入所有线程才能继续。下面是我写的,它是有效的,但它似乎效率低下,我不知道如何做,因为这是我第一次体验多线程Python 多线程用户提示,python,multithreading,python-2.7,user-input,Python,Multithreading,Python 2.7,User Input,我有两个线程同时运行,在后台做一些事情,但是程序到达一个点,需要用户输入所有线程才能继续。下面是我写的,它是有效的,但它似乎效率低下,我不知道如何做,因为这是我第一次体验多线程 global userPromptFlag = 1 # first thread to reach this condition prompts the user for info if (userPromptFlag == 1): userPromptFlag
global userPromptFlag = 1
# first thread to reach this condition prompts the user for info
if (userPromptFlag == 1):
userPromptFlag = 0
self.userPrompts()
else:
# other threads wait until user finishes entering prompts
while promptsFinished == 'n':
pass
我不喜欢两个线程同时达到这种状态的可能性很小,尽管在我的许多测试中还没有出现这种情况。我也不喜欢其他线程在while循环中等待用户输入所需信息,但我们还不必担心这一点,除非您想把它作为一个额外的问题来解决:D使用事件作为障碍。第一个线程将清除该事件,其他线程将等待,直到再次设置该事件
import threading
prompt_lock = threading.Lock()
prompt_event = threading.Event()
prompt_event.set()
# first thread to reach here prompts the user for info
first = False
with prompt_lock:
if prompt_event.is_set():
prompt_event.clear()
first = True
if first:
try:
self.userPrompts()
finally:
prompt_event.set()
else:
prompt_event.wait()
我认为在这里举行一次会议是合适的。