ID generator with local static variable - thread-safe?

c, c++, thread-safety

Solution

No, it won't. Your processor will need to do the following steps to execute this code:

- Fetch value of ID from memory to a register

- Increment the value in the register

- Store the incremented value to memory

If a thread switch occurs during this (non atomic) sequence, the following can happen:

- Thread a fetches the value 1 to a register

- Thread a increments the value, so the register now contains 2

- Context switch

- Thread b fetches the value 1 (which is still in memory)

- Context switch

- Thread a stores 2 to memory and returns

- Context switch

- Thread b increments the value it has stored in its register to 2

- Thread b (also) stores the value 2 to memory and returns 2

So, both threads return 2.

Problem

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?

Original source