I wrote the program
#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;
}
Here std::cin statement would wait for the console for input and will go for sleep mode until we provide some input and press Enter.
I want std::cin statement to go for timeout after 10 seconds(if user doesn't enter any data between 10 seconds then compiler would start executing the next statement of the program present below std::cin statement.
I am able to solve it using multithreading mechanism. Below is my code:
#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);
}
But here I am facing a problem. Due to the sleep function either user inputs value or not the sleep function by default sleeps for 10 seconds. This is where I am lagging.
How do I solve this problem like using(signals,binary semaphores etc..). Please relate your answer w.r.t my solution(i.e multithreading).
Any information is most welcome...
See Question&Answers more detail:os