diff --git a/style.md b/style.md index 03d489a..145b844 100644 --- a/style.md +++ b/style.md @@ -417,6 +417,27 @@ TEST_CASE("Server accepts connections") { - `std::latch`, `std::barrier`, futures/promises - RAII guards and resource management +### Multithreading Test Correctness +- **Force concurrent execution** - Thread creation takes time, so work often completes sequentially before threads start +- **Use std::latch to synchronize thread startup** - Ensures all threads begin racing simultaneously +```cpp +// BAD: Race likely over before threads start +std::atomic counter{0}; +for (int i = 0; i < 4; ++i) { + threads.emplace_back([&]() { counter++; }); // Probably sequential +} + +// GOOD: Force threads to race simultaneously +std::atomic counter{0}; +std::latch start_latch{4}; +for (int i = 0; i < 4; ++i) { + threads.emplace_back([&]() { + start_latch.count_down_and_wait(); // All threads start together + counter++; // Now they actually race + }); +} +``` + --- ## Build Integration