プログラムを書きました
#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 キーを押すまでスリープ モードになります。
std::cin ステートメントが 10 秒後にタイムアウトになるようにしたい (ユーザーが 10 秒の間にデータを入力しない場合、コンパイラは 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 秒間スリープしないかのいずれかです。これは私が遅れているところです。
(シグナル、バイナリセマフォなど)を使用してこの問題を解決するにはどうすればよいですか。あなたの答えを私の解決策(つまりマルチスレッド)に関連付けてください。
どんな情報でも大歓迎です...