用户提示多线程 [英] User prompts with multithreading

查看:57
本文介绍了用户提示多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个线程同时运行,在后台"执行操作,但随后程序到达需要用户输入才能继续运行的点.下面是我写的内容,它可以工作,但它似乎效率低下,我不知道该怎么做,因为这是我第一次使用多线程.

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

我不喜欢两个线程同时达到该条件的可能性很小的事实,尽管在我的许多测试中还没有发生这种情况.我也不喜欢在 while 循环中等待用户输入所需信息的其他线程,但我们不必担心(除非您想将其作为奖励问题解决:D)

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)

推荐答案

使用事件作为障碍.第一个线程将清除该事件,其他线程将等待它再次设置.

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

这篇关于用户提示多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆