I am writing a class which periodically has to check, if the data it manages is too old, if so it should delete it.
I am new to the C++11
multithreading library and I have the following questions:
Is such a periodic task better suited for
std::thread
orstd::async
?If we use
std::async
how long is the cleanUp function running? Until the DataManager gets destroyed?Is it considered good design to spin off an
std::async
orstd::thread
in the constructor?
class DataManager {
public:
DataManager() {
handle = std::async(
std::launch::async,
&DataManager:cleanUp, this);
}
...
void DataManager::cleanUp() {
while (true) {
std::this_thread::sleep_for(
std::chrono::seconds(DATA_COLLECTOR_PERIOD));
for (auto& d: dataCollection) {
if (d.isTooOld()) {
dataCollection.remove(d);
}
}
}
}
private:
std::future<void> handle;
std::vector<Foo> dataCollection;
};
while (true)
and contains no other exit condition)