Search code examples
pythonmultithreadingpython-2.7user-input

User prompts with multithreading


I have a couple threads running at once, doing things in the "background", but then the program reaches a point where it needs user input for all the threads to continue. Below is what I have written, and it works, but it seems inefficient and I'm not sure how else to do it as this is my first experience with multi-threading.

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

I don't like the fact that there is a small chance that two threads can reach the condition at the same time, though it hasn't happened yet in my many tests. I'm also not a fan of the other threads sitting in that while loop waiting for the user to enter the required information, but we don't have to worry about that yet (unless you want to address it as a bonus question :D)


Solution

  • Use a Event as a barrier. The first thread will clear the event and the other threads will wait until it is set again.

    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()