sim*_*mon 5 windows multithreading stdin c++11 msvc12
我有一个应用程序,它使用线程中的getline()从标准输入读取数据.我想从主线程关闭应用程序,而getline仍然阻止其他线程.怎么能实现这一目标?
我不想强迫用户必须按ctrl-Z来关闭stdin和应用程序.
到目前为止,我已尝试使用Windows 8.1 64bit,v120平台工具集上的编译器设置(RuntimeLibrary =/MT):
*更新*
*更新2:解决方案*
显示问题的示例代码:
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
int main(int argc, char *argv[])
{
bool stop = false;
std::thread *t = new std::thread([&]{
std::string line;
while (!stop && std::getline(std::cin, line, '\n')) {
std::cout << line;
}
});
std::this_thread::sleep_for(std::chrono::seconds(1));
stop = true;
// how to stop thread or make getline to return here?
return 0;
}
Run Code Online (Sandbox Code Playgroud)
writeConsoleInput() 可以使 std::getline 从阻塞读取中返回,因此即使使用 /MT 编译器选项也可以解决问题。
#include <Windows.h>
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <atomic>
int main(int argc, char *argv[])
{
std::atomic_bool stop;
stop = false;
std::thread t([&]{
std::string line;
while (!stop.load() && std::getline(std::cin, line, '\n')) {
std::cout << line;
}
});
std::this_thread::sleep_for(std::chrono::seconds(1));
stop = true;
DWORD dwTmp;
INPUT_RECORD ir[2];
ir[0].EventType = KEY_EVENT;
ir[0].Event.KeyEvent.bKeyDown = TRUE;
ir[0].Event.KeyEvent.dwControlKeyState = 0;
ir[0].Event.KeyEvent.uChar.UnicodeChar = VK_RETURN;
ir[0].Event.KeyEvent.wRepeatCount = 1;
ir[0].Event.KeyEvent.wVirtualKeyCode = VK_RETURN;
ir[0].Event.KeyEvent.wVirtualScanCode = MapVirtualKey(VK_RETURN, MAPVK_VK_TO_VSC);
ir[1] = ir[0];
ir[1].Event.KeyEvent.bKeyDown = FALSE;
WriteConsoleInput(GetStdHandle(STD_INPUT_HANDLE), ir, 2, &dwTmp);
t.join();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
759 次 |
| 最近记录: |