4 ms·
/// ---------------------------------------------------------------------------- /// latches are great for multi-threaded tests with following sequence of s
by signa11 5y ago
/// ----------------------------------------------------------------------------
/// latches are great for multi-threaded tests with following sequence of steps
/// 1. setup test data
/// 2. create a latch
/// 3. create test threads each decrementing the latch-count
/// 4. when all threads have reached the latch, they are unblocked.
///
/// sligtly verbose commented code to illustrate this
void foo()
{
/// --------------------------------------------------------------------
/// create a latch with non-zero-count
unsigned const thread_count=...;
std::latch done(thread_count);
my_data data[thread_count];
std::vector<std::jthread> threads;
/// --------------------------------------------------------------------
/// threads decrement count as they are created
for(unsigned i=0;i<thread_count;++i)
threads.push_back(std::jthread([&,i]{
data[i]=make_data(i);
done.count_down();
do_more_stuff();
}));
/// --------------------------------------------------------------------
/// others wait for latch to be signalled, when the count reaches zero,
/// latch is permanently signalled, and threads are woken
done.wait();
process_data();
}
have fun ?
- klodolph 5y agoI'm just saying in Go, the equivalent construct (WaitGroup) does not require you to figure out the count ahead of time. There's an idiom of: var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() }() wg.Wait() The middle part of the block can be done freely, you don't have to count the threads beforehand.
- quietbritishjim 5y agoI realise this was just a quick example, but just to be clear, the latch is tied to the number of work items not the number of threads. If you had a thread pool (or single thread) with a queue, you can happily push any number of work items on to it and use the latch to wait until they're all complete, regardless of which threads they're handled in (or even if the jobs are interleved with other jobs from some other source).
- signa11 5y agoyes ofcourse!
- Koshkin 5y ago> when all threads have reached the latch, they are unblocked The phrasing is somewhat confusing: it is the waiting thread, not "they", that gets unblocked (count_down does not block).