提问人:Less White 提问时间:3/22/2022 更新时间:3/22/2022 访问量:463
如何在成员变量中实例化 std::async 创建的未来?
How to instantiate a future created by std::async in a member variable?
问:
当我在下面尝试将返回的未来添加到成员变量中时,我做错了什么?std::async
class PrinterDriver
{
std::vector<std::future<void>> m_PendingFutures;
public:
int DriverThread()
{
// Do something
}
void Start()
{
m_PendingFutures.emplace_back(
std::async(std::launch::async,
&PrinterDriver::DriverThread, this));
}
}
我不明白这个错误,也无法找到如何解决它:
错误 C2664:“std::future::future(std::future &&) noexcept”:无法转换参数 1 从 '_Ty' 到 'std::future &&'
下面是完整的代码,作为我想使用它的上下文:
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <future>
#include <thread>
class PrinterDriver
{
std::mutex m_stop_driver_mutex;
std::condition_variable_any m_StopDriverEvent;
std::vector<std::future<void>> m_PendingFutures;
public:
~PrinterDriver() = default;
int DriverThread()
{
printf("Printer driver started\n");
auto quit = false;
while (!quit)
{
// Wait 200 ms except if we are signaled to stop
{
using namespace std::chrono_literals;
std::unique_lock<std::mutex> lock(m_stop_driver_mutex);
const auto cv_status = m_StopDriverEvent.wait_for(lock, 200ms);
quit = (cv_status == std::cv_status::no_timeout);
}
}
printf("Printer driver stopped\n");
return 0;
}
void Start()
{
// How to instantiate a future created by std::async in a member variable ?
// Error C2664: 'std::future<void>::future(std::future<void> &&) noexcept':
// cannot convert argument 1 from '_Ty' to 'std::future<void> &&'
m_PendingFutures.emplace_back(std::async(std::launch::async, &PrinterDriver::DriverThread, this));
}
void Stop()
{
std::unique_lock<std::mutex> lock(m_stop_driver_mutex);
m_StopDriverEvent.notify_all();
for (auto&& future_handle : m_PendingFutures)
{
future_handle.get();
}
m_PendingFutures.clear();
}
};
int main()
{
PrinterDriver driver;
driver.Start();
std::this_thread::sleep_for(std::chrono::seconds(2));
driver.Stop();
return 0;
}
答: 暂无答案
评论
int
void
std::future<void>
->std::future<int>
void DriverThread()