【问题标题】:Choice between thread: time expired and user input线程之间的选择:过期时间和用户输入
【发布时间】:2014-07-17 08:31:54
【问题描述】:

我正在编写一个简单的函数,当被调用时,它允许执行 2 个不同的操作(独占)。

所以有两个线程。 User_choice 等到用户插入输入,Time_choice 等到时间到期。

choice_done 共享变量表示,如果为真,则一个线程已经启动并阻塞(它不做任何事情!)另一个;而thread_done 表示,如果为真,则该线程(哪个无关紧要)已经完成,所以func() 等待一个线程完成。

这是代码。
在程序执行期间,func 过程将被调用更多次。

各种user_choice 线程将永远在getline 上等待!这是个问题吗?如果在四次程序调用func() 并且用户没有插入任何内容后,用户第五次插入“是”怎么办?
每个user_choice 线程都会继续执行吗?如何杀死等待线程?还有其他解决方案吗?

如何在func() 内部等待线程将thread_done 设置为true?

bool choice_done = false;
bool thread_done = false;

void func(){
   boost::thread t1(boost::bind( time_choice() ));
   boost::thread t2(boost::bind( user_choice() ));

   //whait untile thread_done == true
   do something...
}

// Time choice thread
void time_choice(){

    sleep(5);

    if(choice_done == false){

        printf("Automatic choice\n");
        choice_done == true;

        do something...

        thread_done = true;
    } 
}


// User choice thread
void user_choice(){        

    printf("Start emergency procedure?\n");

    string tmp;
    getline(cin, tmp);

    if((tmp.compare("yes") == 0) && (choice_done == false)){

        printf("Manual choice\n");
        choice_done == true;

        do something... 

        thread_done = true;           
    } 
}

【问题讨论】:

    标签: c++ multithreading getline choice


    【解决方案1】:

    必须为计时器创建线程通常是次优设计的标志。它不能很好地扩展(想象有数千个计时器)并且代码变得多线程并且没有充分的理由变得更加复杂。另外,sleep is not thread-safe on Linux

    只需使用一个带有select 和超时的线程。 select 将在 STDIN_FILENO 上同时等待用户输入和超时。

    或者,更好的是,使用第 3 方事件解复用库,例如​​ libeventboost::asio

    【讨论】:

    • @gepeppe 你知道的。当STDIN_FILENO 准备好读取时,读取它不会阻塞(但您仍然需要使用非阻塞I/O 来读取整行)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多