#Is this a reliable way to test for multiple threads entering the critical section?
12 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.
void runSomething() {
static std::atomic<size_t> threadCount(0);
threadCount += 1;
run_critical_section(args...);
if (threadCount.load() != 1) {
std::cerr << "race condition caught, terminating...\n";
exit(1);
}
threadCount -= 1;
}
I don't see any issue with the approach
the problem is that the UB has already occured at the point where you're checking
but the detection is correct
it also gives false positives for when threadCount has been incremented, but the critical section hasn't been entered yet, but that's a really minor issue and doesn't look preventable
Arguably you don't even attempt to detect multiple threads entering the critical section. You should really check before entering, not (only) after.
a.k.a. the atomic counter should be placed at the first line in the actual critical section, right?
you could use an atomic fetch-add to check if you're entering the critical section at the same time as another thread
if (threadCount++ != 0) {
// error because race condition
}
critical_section();
threadCount--;
!solved