Question

Please assume a mulithreaded function with this section of code:

if( !executing_singular_process ){
    executing_singular_process = true;
    singular_process();
}
executing_singular_process = false;

where executing_singular_process is a std::atomic<bool>.

Does the possibility exist where one thread will execute if( !executing_singular_process ) in the precise moment in another thread between if( !executing_singular_process ) and executing_singular_process = true;?

If so, how can an atomic bool be used to ensure that one process will only ever be executed by one thread?

Was it helpful?

Solution

Yes, it can happen that two threads execute the function singular_process() at the same time. You can avoid this problem with compare_exchange:

bool expected = false;
if (executing_singular_process.compare_exchange_strong(expected, true)) {
    singular_process();
    executing_singular_process = false;
}

OTHER TIPS

besides what was pointed out in the answer of nosid, your code has another huge problem, even without the security leak you basically found yourself (it is fixed in nosids answer as well)

Let's assume you are having 3 threads running over your code:

Thread A gets to the atomic bool, sets it to true, executes singular process. Now thread B arrives, finds a true. The thread skips singular_process, but now sets your atomic bool to true! But Thread A may be still working on singular process! So when now thread C arrives at the initial check, it is told by your bool, that it is entirely okay to execute singular process. And suddenly A and C are executing your singular process at the same time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top