我编写了这个程序。
#include<iostream>
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键后才进入睡眠模式。
我希望在10秒后,如果用户没有输入任何数据,std::cin语句会超时,编译器会执行在std::cin语句下面的程序的下一条语句。
我可以使用多线程机制来解决这个问题。以下是我的代码:
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<iostream>
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<<"cancelling thread"<<endl;
res=pthread_cancel(a_thread);
cout<<"input value="<<input_value<<endl;
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秒钟。这就是我的滞后之处。
如何解决这个问题,比如使用(信号、二进制信号量等)。请将您的答案与我的解决方案相关联(即多线程)。
欢迎提供任何信息...