如何从std :: vector自动删除已完成的期货 [英] How can completed futures be automatically erased from std::vector
本文介绍了如何从std :: vector自动删除已完成的期货的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中,mEventExecutors是 std :: vector< std :: future< void>>
。我希望能够在完成交易后从向量中删除其期货。
In the following exampl, mEventExecutors is a std::vector<std::future<void>>
. I would like to be able to remove the futures from the vector, as they complete. Can this be done?
void RaiseEvent(EventID messageID)
{
mEventExecutors.push_back(std::move(std::async([=]{
auto eventObject = mEventListeners.find(messageID);
if (eventObject != mEventListeners.end())
{
for (auto listener : eventObject->second)
{
listener();
}
}
})
));
}
推荐答案
不要使用<$我认为c $ c> std :: async 是简单的解决方案,请改用 std :: thread
。
Don't use std::async
is the easy solution in my opinion, and use std::thread
instead.
不过,您需要注意,您的代码当前有很多数据争用。考虑使用其他互斥锁或其他某种技术来防止它们。
You need to be careful though, your code currently has a lot of data races. Consider using another mutex or some other technique to prevent them.
std::thread{[=]() {
// Task is running...
auto eventObject = mEventListeners.find(messageID);
if (eventObject != mEventListeners.end())
{
for (auto listener : eventObject->second)
{
listener();
}
}
}.detach(); // detach thread so that it continues
这篇关于如何从std :: vector自动删除已完成的期货的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文