From 8a83338769fa9c7c4c2588c1bd6178b62b5eaef4 Mon Sep 17 00:00:00 2001 From: Andrew Noyes Date: Sat, 23 Aug 2025 09:02:45 -0400 Subject: [PATCH] Add "force concurrent execution" to style guide --- style.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) 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