The std::latch was made to simplify when you want one main thread to wait for all others to finish. Also, you can use it to make all threads stop at a certain point and make them all continue when all threads have caught up. Let’s have a look at how you might use them:
#include <iostream>
#include <thread>
#include <latch>
#include <vector>
constexpr int num_threads = 7;
void proc(int id, std::latch& latch) {
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Processing finished " << id << std::endl;
latch.count_down();
}
int main() {
// Create a latch with the count equal to the # of threads
std::latch latch(num_threads);
std::vector<std::thread> threads;
for (int i = 0; i < num_threads; i++) {
threads.push_back(std::thread(proc, i, std::ref(latch)));
}
// Wait for all threads to complete
latch.wait();
std::cout << "All processes finished\n";
for (auto& thread : threads) {
thread.join();
}
return 0;
}
And here is the same code but with promise/futures:
#include <iostream>
#include <thread>
#include <vector>
#include <future>
// Worker thread function
void proc(std::promise<void> &&promise) {
std::this_thread::sleep_for(std::chrono::seconds(2));
promise.set_value();
}
int main() {
const int num_threads = 7; // number of worker threads
std::vector<std::thread> threads;
std::vector<std::future<void>> futures;
// Start worker threads
for (int i = 0; i < num_threads; ++i) {
std::promise<void> promise;
futures.push_back(promise.get_future());
threads.push_back(std::thread(proc, std::move(promise)));
}
// Wait for all worker threads to complete
for (auto &future : futures) {
future.get();
}
// Join all threads
for (auto &thread : threads) {
if (thread.joinable()) {
thread.join();
}
}
std::cout << "All processes finished.\n";
return 0;
}
The std::latch makes the code nicer, but the performance is fairly identical. I’ve tried a bunch of more complex tests and I can’t see any major difference in performance. So really, std::latch is there just to make the code look nicer, and for you to learn a new keyword!
Leave a Reply