c++ - How to define a non blocking input in C++
问题描述
I'm making a multithread application in C++. In particular, a secondary thread is involved in input operations, the problem is that std::cin is a blocking instruction and this create some problems in the execution flow of my program. If main thread end its execution, secondary thread should do the same, but it's blocked on std::cin, so user has to insert something to let the program to end. It's possible to overcome this problem?
Here's the code:
#include <iostream>
#include <future>
#include <string>
#include <chrono>
#include <thread>
#include <atomic>
std::atomic<bool> interrupt(false);
std::string get_input(){
std::cout << "Insert a new command: ";
std::string cmd;
std::cin >> cmd;
return cmd;
}
void kill_main_thread(){
std::this_thread::sleep_for(std::chrono::milliseconds(5000));
interrupt = true;
}
int main() {
std::thread new_thread (kill_main_thread); // spawn new thread that calls foo()
while(1) {
if ( interrupt ) {
return 0;
}
std::future<std::string> fut = std::async(get_input);
if ( fut.wait_for(std::chrono::seconds(500)) == std::future_status::timeout ){
std::string cmd = fut.get();
if ( cmd == "close") std::cout << "close command\n";
else if ( cmd == "open") std::cout << "open command\n";
else std::cout << "not recognized command\n";
}
}
return 0;
}
So basically I found three possible solutions for my purpose:
1.) Is it possible to realize a non blocking std::cin? 2.) Is there any interrupt or kill signal that will stop execution of the secondary thread? 3.) Is it possible to virtualize in some way std::cin? In kill_main_thread() function I tried it by using this instruction:
void kill_main_thread(){
...
...
std::istringstream iss;
std::cin.rdbuf(iss);
}
But secondary thread is still blocked on std::cin.
I also tried by using getch() function of conio.h library to create a non blocking input function to replace std::cin, but first of all my application should preferly work on different OS and secondary it create a bit of problem with managing of console because I need to change every std::cout of my program in this way
解决方案
推荐阅读
- angular - highcharts 中的图表选项未从 ngoninit 中的函数调用更新
- unit-testing - NUnit 延迟约束似乎在 Unity3d 中不起作用
- swift - 下一个对象实例 IGListKit
- python - 数据集中的空值
- python - 如何在没有 /F 的 Windows 上使用 taskkill 杀死 python
- shell - 在 Makefile 中拆分和剪切字符串
- yaml - 无法将示例添加到 YAML 文件
- android - Android位图压缩webp到jpg不改变mime类型
- python - 为许多掩码获取每个掩码 np.array 的最大值的最快方法?
- javascript - 引入“顶级等待”后是否应该将 JS 函数定义为异步?