User prompts with multithreading

不羁的心 提交于 2021-02-11 12:17:05

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/59865825/user-prompts-with-multithreading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!