#Is this a reliable way to test for multiple threads entering the critical section?

12 messages · Page 1 of 1 (latest)

vapid cove
#

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;
}

vapid quartzBOT
#

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;
}
Kolio98
near berry
#

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

grim smelt
#

Arguably you don't even attempt to detect multiple threads entering the critical section. You should really check before entering, not (only) after.

vapid cove
near berry
#
if (threadCount++ != 0) {
    // error because race condition
}
critical_section();
threadCount--;
vapid cove
#

!solved