cin java,使用std :: cin语句进行自动超时

我写了这个程序

#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秒 . 这是我落后的地方 .

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

任何信息都是最受欢迎的......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值