微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

检查input和睡眠提升线程

我试图build立一个线程,检查用户input,如果input等于“退出”,它会closures所有其他线程。

我使用cin的方式似乎停止了线程。 线程应该运行,检查用户input,如果有,并等于“退出”,closuresrunProcesses 。

这是我的代码不能按预期工作,因为“新行停止”从不打印,“运行”只打印一次:

void check_for_cin() { while ( runProcesses ) { cout << "running"; string input; std::getline( std::cin,input ); //while ( std::getline( std::cin,input ) ) { if ( !input.empty() ) { if ( input == "exit" ) { runProcesses = false; cout << "exiting" << ",run processes: " << runProcesses; } } cout << "newline stopped"; boost::this_thread::sleep( boost::posix_time::seconds( 1 ) ); } cout << "no longer checking for input"; }

我的意图怎么做?

如何使用postThreadMessage来传递一个结构体

Windows上的微秒分辨率时间戳

Windows 7:利用自动提升来提升我自己的进程?

如何指定一个特定的网卡用于用c ++编写的应用程序(boost asio)

Boost.Asio的可扩展性

在ubuntu core 14.04上安装libboost-all-dev时依赖性失败

有没有办法确定一个date/时间不存在?

c ++ boost计算在函数中花费的时间

LNK2038:检测到“boost_log_abi”不匹配:值“v2s_mt_nt5”与值“v2s_mt_nt6”不匹配

C ++ boost :: thread,如何在类中启动一个线程

看看Asio的文件描述符服务对象。

Posix有一个“反应堆”风格异步,所以你实际上不需要线程来实现异步性。

我的例子显示一个读取循环,当“退出”键入/或/超时过期(10s)时退出

#include <boost/asio.hpp> #include <boost/asio/posix/stream_descriptor.hpp> boost::asio::io_service my_io_service; boost::asio::posix::stream_descriptor in(my_io_service,::dup(STDIN_FILENO)); boost::asio::deadline_timer timer(my_io_service); // handle timeout void timeout_expired(boost::system::error_code ec) { if (!ec) std::cerr << "Timeout expiredn"; else if (ec == boost::asio::error::operation_aborted) // this error is reported on timer.cancel() std::cerr << "Leaving early :)n"; else std::cerr << "Exiting for another reason: " << ec.message() << "n"; // stop the reading loop in.cancel(); in.close(); } // set timeout timer void arm_timeout() { timer.expires_from_Now(boost::posix_time::seconds(10)); timer.async_wait(timeout_expired); } // perform reading loop void reading_loop() { std::cerr << "(continueing input...)n"; static boost::asio::streambuf buffer; // todo some encapsulation :) async_read_until(in,buffer,'n',[&](boost::system::error_code ec,size_t bytes_transferred) { if (!ec) { std::string line; std::istream is(&buffer); if (std::getline(is,line) && line == "exit") ec = boost::asio::error::operation_aborted; else reading_loop(); // continue } if (ec) { std::cerr << "Exiting due to: " << ec.message() << "n"; // in this case,we don't want to wait until the timeout expires timer.cancel(); } }); } int main() { arm_timeout(); reading_loop(); my_io_service.run(); }

在Windows上,您可以使用等效的Windows流句柄

您可以通过在多个线程上运行my_io_service.run()来简单地添加线程。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐