我写了这个程序
#include
using namespace std;
int n;
int main(int argc, char *argv[])
{
std::cout << "Before reading from cin" << std::endl;
// Below reading from cin should be executed within stipulated time
bool b=std::cin >> n;
if (b)
std::cout << "input is integer for n and it's correct" << std::endl;
else
std::cout << "Either n is not integer or no input for n" << std::endl;
return 0;
}
这里std :: cin语句将等待控制台输入并进入休眠模式,直到我们提供一些输入并按Enter键 .
我希望std :: cin语句在10秒后超时(如果用户在10秒之间没有输入任何数据,那么编译器将开始执行std :: cin语句下面的程序的下一个语句 .
我能够使用多线程机制解决它 . 以下是我的代码:
#include
#include
#include
#include
using namespace std;
void *thread_function(void *arg);
int input_value;
int main(int argc, char *argv[])
{
int res;
pthread_t a_thread;
void *thread_result;
res=pthread_create(&a_thread,NULL,thread_function,NULL);
if(res!=0){
perror("Thread creation error");
exit(EXIT_FAILURE);
}
//sleep(10);
cout<
res=pthread_cancel(a_thread);
cout<
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg)
{
int res;
res=pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
if(res!=0){
perror("Unable to set pthread to cancel enbable state");
exit(EXIT_FAILURE);
}
cin>>input_value;
pthread_exit(&input_value);
}
但在这里我遇到了一个问题 . 由于睡眠功能要么用户输入值,要么睡眠功能默认睡眠10秒 . 这是我落后的地方 .
如何使用(信号,二进制信号量等)来解决这个问题 . 请将您的答案与我的解决方案(即多线程)联系起来 .
任何信息都是最受欢迎的......