gpt4 book ai didi

c++ - 检查输入和 sleep boost 线程

转载 作者:太空狗 更新时间:2023-10-29 12:16:48 26 4
gpt4 key购买 nike

我正在尝试构建一个线程来检查用户输入,如果输入等于“退出”,它会关闭所有其他线程。

我使用 cin 的方式似乎停止了线程。线程应该运行,检查用户输入,如果有任何输入并且等于“退出”,则关闭 runProcesses

这是我的代码,它没有按预期工作,因为从未打印“换行停止”,“运行”只打印一次:

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";
}

如何实现我的意图?

最佳答案

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

Posix 具有“ react 器”风格的异步性,因此您实际上不需要线程来实现异步性。

我的示例显示了一个读取循环,该循环在键入“exit”时/或/在超时到期(10 秒)时退出。

#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 expired\n";
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 Stream Handle

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

关于c++ - 检查输入和 sleep boost 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21842004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com