c++ - 使用 std::cin 语句使自动超时

标签 c++ linux multithreading

我写的程序

#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);
 }

但是这里我遇到了一个问题。由于 sleep 功能,用户输入值或不输入值,默认情况下 sleep 功能会 sleep 10 秒。这是我落后的地方。

我如何解决这个问题,比如使用(信号、二进制信号量等)。请将您的答案与我的解决方案(即多线程)联系起来。

欢迎提供任何信息...

最佳答案

因为你在 POSIX 机器上,你可以使用例如select检查标准输入上是否有任何内容:

fd_set fds;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds)

timeval timeout;
timeout.tv_sec = 5;   // A five-second timeout
timeout.tv_usec = 0;

int rc = select(STDIN_FILENO + 1, &fds, nullptr, nullptr, &timeout);
if (rc < 0)
    perror("select");
else if (rc == 0)
{
    // Timeout
}
else
{
    // There is input to be read on standard input
}

使用 poll(正如 Basile Starynkevitch 所建议的那样),它可以像这样完成:

struct pollfd poller;
poller.fd = STDIN_FILENO;
poller.events = POLLIN;
poller.revents = 0;

int rc = poll(&poller, 1, 5);  // Poll one descriptor with a five second timeout
if (rc < 0)
    perror("select");
else if (rc == 0)
{
    // Timeout
}
else
{
    // There is input to be read on standard input
}

关于c++ - 使用 std::cin 语句使自动超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18589140/

相关文章:

c++ - 作为好友的成员函数 : Is the book Lippman 5th wrong?

linux - Ubuntu 16.04 鼠标光标闪烁并消失

python - 尝试构建 docker 镜像时无法获取错误(运行 apt-get 更新时)

objective-c - 处理线程中变量的问题

c++ - 下面的代码是如何进行类型转换的?

c++ - 无法使用 dyn.load windows 7 64bit 在 R 中加载 dll 文件

java - 我可以通过 JNI 调试以 native 代码创建的 JVM 吗?

linux - 根据严重性将 kea-dhcp4 服务器日志推送到不同的文件

ios - 使用 NSURLConnection 是否需要考虑线程安全? - iOS

java - 使用java线程编写一个程序来打印以下序列2 3 4 6 6 9 8 12 10(序列中2和3的倍数)