Man*_*era 0 c++ multithreading user-input cin console-application
如何在不导致代码停止执行的情况下输入输入?我一直在寻找答案,在过去的20分钟内没有结果.
cin >> string; 暂停代码AFAIK.
我需要使用多线程,还是有更好的方法?(我甚至不知道多线程是否有效.)
我最近开始学习c ++,至少可以说是初学者,所以请详细解释并包含我可能需要的任何库,谢谢.
下面是一个示例,说明如何>>使用多线程与另一个调用并行使用标准输入流中的标记.
#include <iostream>
#include <thread>
#include <future>
int main() {
// Enable standard literals as 2s and ""s.
using namespace std::literals;
// Execute lambda asyncronously.
auto f = std::async(std::launch::async, [] {
auto s = ""s;
if (std::cin >> s) return s;
});
// Continue execution in main thread.
while(f.wait_for(2s) != std::future_status::ready) {
std::cout << "still waiting..." << std::endl;
}
std::cout << "Input was: " << f.get() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这里std::async使用launch参数的调用std::launch::async在不同的线程上异步运行任务.std::async返回并行运行的任务句柄,称为future.此未来可用于检查任务是否完成.也可以std::future使用成员函数从对象返回任务的结果std::future::get.
我传递给的任务std::async是一个简单的lambda表达式,它创建一个字符串,从流中读取一个标记到字符串中并返回它(这""s是一个在C++ 14中引入的标准文字,它返回一个空std::string对象).
在调用std::async主线程后继续执行语句(与异步运行的任务并行).在我的示例while中,执行一个循环,只是等待异步任务完成.注意std::future::wait_for每次迭代时只使用2秒的块.std::future::wait_for返回可以进行比较的状态,以检查任务是否完成.
最后,调用std::future::get将返回异步运行任务的结果.如果我们还没有等待任务完成,则调用将阻塞,直到结果准备好.
注意不要同时读取主线程中的标准输入(并行),因为读取调用不是原子事务,数据可能是乱码.
| 归档时间: |
|
| 查看次数: |
9532 次 |
| 最近记录: |