#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
int main() {
std::cout << "Example 1: Basic latch synchronization\n";
{
constexpr int kNumThreads = 4;
std::atomic<int> readyCount(0);
for (int i = 0; i < kNumThreads; ++i) {
taskSet.
schedule([&latch, &readyCount, i]() {
readyCount.fetch_add(1, std::memory_order_relaxed);
std::cout << " Thread " << i << " ready\n";
});
}
std::cout << " All " << readyCount.load() << " threads synchronized\n";
}
std::cout << "\nExample 2: Separate count_down and wait\n";
{
constexpr int kNumWorkers = 3;
std::vector<int> results(kNumWorkers, 0);
for (int i = 0; i < kNumWorkers; ++i) {
taskSet.
schedule([&workComplete, &results, i]() {
results[static_cast<size_t>(i)] = (i + 1) * 10;
});
}
std::cout << " Results: ";
for (int r : results) {
std::cout << r << " ";
}
std::cout << "\n";
}
std::cout << "\nExample 3: Non-blocking try_wait check\n";
{
std::cout <<
" Before count_down, try_wait() = " << (latch.
try_wait() ?
"true" :
"false")
<< "\n";
std::cout <<
" After count_down, try_wait() = " << (latch.
try_wait() ?
"true" :
"false")
<< "\n";
}
std::cout << "\nExample 4: Phased computation with multiple latches\n";
{
constexpr int kNumThreads = 4;
std::atomic<int> phase1Sum(0);
std::atomic<int> phase2Sum(0);
for (int i = 0; i < kNumThreads; ++i) {
phase1Sum.fetch_add(i + 1, std::memory_order_relaxed);
int localResult = phase1Sum.load() * (i + 1);
phase2Sum.fetch_add(localResult, std::memory_order_relaxed);
});
}
std::cout << " Phase 1 sum: " << phase1Sum.load() << " (1+2+3+4 = 10)\n";
std::cout << " Phase 2 sum: " << phase2Sum.load() << " (10*1 + 10*2 + 10*3 + 10*4 = 100)\n";
}
std::cout << "\nExample 5: Latch as a one-shot start gate\n";
{
std::atomic<int> workersStarted(0);
for (int i = 0; i < 5; ++i) {
taskSet.
schedule([&startGate, &workersStarted]() {
workersStarted.fetch_add(1, std::memory_order_relaxed);
});
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
std::cout << " Workers before gate opens: " << workersStarted.load() << "\n";
std::cout << " Workers after gate opens: " << workersStarted.load() << "\n";
}
std::cout << "\nAll Latch examples completed successfully!\n";
return 0;
}
void schedule(F &&f, bool skipRecheck=false)
DISPENSO_DLL_ACCESS bool wait()
void arrive_and_wait() noexcept
void count_down(uint32_t n=1) noexcept
bool try_wait() const noexcept
void wait() const noexcept