Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::call_once concurrent calls behavior

Tags:

c++

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

like image 846
CmedCmbadi Avatar asked Oct 12 '25 16:10

CmedCmbadi


1 Answers

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.

like image 92
KamilCuk Avatar answered Oct 14 '25 06:10

KamilCuk