I’m trying to execute a piece once and I’m using std::call_once
to achieve this. Now, my question is the following, assuming that the executed piece of code takes a while to complete, what would be the behavior of the second caller, if the first caller hasn’t completed yet.
Will it return immediately or will it wait until the first complete before returning.
Ps: Both calls are from different threads and first call will succeed.
I did a small test to check the behavior. The second call returned after the first call was completed, but i couldn’t find any info whether this behavior is from the c++ standard
From https://eel.is/c++draft/thread#once.callonce :
Synchronization: For any given once_flag: all active executions occur in a total order; completion of an active execution synchronizes with the start of the next one in this total order; and the returning execution synchronizes with the return from all passive executions.
Means only one call_once
will enter at a time. So if you call it twice, the second one will wait for the first one to complete.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With