Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多线程用户提示_Python_Multithreading_Python 2.7_User Input - Fatal编程技术网

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()
我认为在这里举行一次会议是合适的。