I have some tasks that need to be performed asynchronously, and the server can't close while there are still tasks running. So I'm trying to store the futures returned by std::async
in a list, but I also don't want to get an infinitely growing list of those. So I want to remove the futures as they're completed.
Here's roughly what I'm trying to do:
// this is a member of the server class
std::list<std::future<void>> pending;
std::list<std::future<void>>::iterator iter = ???;
pending.push_back( std::async( std::launch::async, [iter]()
{
doSomething();
pending.remove( iter );
} );
Here, iter
needs to be pointing to the newly inserted element, but I can't get it before inserting the element (there is no iterator), nor after (since it is passed to the lambda by value). I could make a shared_ptr
to store the iterator, but that seems to be way overkill.
Is there a better pattern for this?
Update: there seems to be another issue with this. When a future attempts to remove itself from the list, it is essentially waiting for itself to complete, which locks everything up. Oops!
On top of that, list destructor empties the list before calling element destructors.
remove
? Yes, I'll need something like that. The push operation is only called from socket listener so that should be synchronized already. – Chastise