Will the following piece of code work as expected in a multi-threaded scenario?
int getUniqueID()
{
static int ID=0;
return ++ID;
}
It's not necessary that the IDs to be contiguous - even if it skips a value, it's fine. Can it be said that when this function returns, the value returned will be unique across all threads?
With C++11, static variables with block scope have an additional guarantee; they will be initialized in a thread-safe way.
Starting in C++11, scoped static initialization is now thread-safe, but it comes with a cost: Reentrancy now invokes undefined behavior.] The rule for static variables at block scope (as opposed to static variables with global scope) is that they are initialized the first time execution reaches their declaration.
They are not thread safe.
No, it won't. Your processor will need to do the following steps to execute this code:
If a thread switch occurs during this (non atomic) sequence, the following can happen:
So, both threads return 2.
No, there is still a potential for races, because the increment is not necessarily atomic. If you use an atomic operation to increment ID, this should work.
If you just need some monotonically increasing (or very close to it) numbers across N threads, consider this (k is some number such that 2^k > N):
int getUniqueIDBase()
{
static int ID=0;
return ++ID;
}
int getUniqueID()
{
return getUniqueIDBase() << k + thread_id;
}
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