multithreading - C++ 控制台应用程序异步接受用户输入
问题描述
我最近偶然发现了这个 链接,我只是尝试了一下,但它并没有像我预期的那样工作。
使用此代码:
#include <atomic>
#include <thread>
#include <iostream>
void ReadCin(std::atomic<bool>& run)
{
std::string buffer;
while (run.load())
{
std::cin >> buffer;
if (buffer == "q")
{
run.store(false);
}
}
}
int main()
{
std::atomic<bool> run(true);
std::thread cinThread(ReadCin, std::ref(run));
while (run.load())
{
// some lengthy operation
}
run.store(false);
cinThread.join();
return 0;
}
在主 While 循环中,我有一个类的对象正在执行一些冗长的操作,我试图用来自用户的字母“q”来停止它。当我输入“q”时,我看到了“run.store(false);” 命中 ReadCin 方法,但这并没有让我脱离主 while 循环。我究竟做错了什么?
解决方案
推荐阅读
- java - 使用批处理侦听器的安全方法
- dart - Flutter 中的状态管理
- c# - 在 TCP 级别拦截 WCF 调用
- json - 如何使用机器人框架处理http请求中的JSON数组
- powershell - GPO 启动 powershell 脚本未执行
- sql-server - 触发器执行时子查询返回超过 1 个值
- php - 没有librabbitmq,同时安装rabbitmq pecl brew php
- vim - Vim Execute Nohlsearch Not Working in Function
- css - 需要拖动条来溢出并适合 div 的全宽吗?
- android - java.lang.NoClassDefFoundError: Failed resolution of: App class on Lenovo K4 Note running android 6, API 23