Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are incrementers / decrementers (var++, var--) etc thread safe?

Inspired by this question: In Complexity Analysis why is ++ considered to be 2 operations?

Take the following psuedo code:

class test
{
   int _counter;
   void Increment()
   {
     _counter++;
   } 
}

Would this be considered thread safe on an x86 architechure? Further more are the Inc / Dec assembly instructions thread safe?

like image 374
JoshBerke Avatar asked Jan 14 '09 16:01

JoshBerke


People also ask

Is increment operator thread-safe?

If you have multiple threads increment or decrementing a variable using the increment or decrement operators, you may not get the desired result. These operators are not thread-safe.

Is i ++ thread-safe in Java?

Question is “is pre increment operator thread safe ?” Ans : No , Why ? because of number of instructions involved. Atomic means single operation , here load/add/store operations need to be performed.

Is C++ thread-safe?

++ is not defined as thread-safe. the existence of Interlocked.


2 Answers

No, incrementing is not thread-safe. Neither are the INC and DEC instructions. They all require a load and a store, and a thread running on another CPU could do its own load or store on the same memory location interleaved between those operations.

Some languages have built-in support for thread synchronization, but it's usually something you have to ask for, not something you get automatically on every variable. Those that don't have built-in support usually have access to a library that provides similar functionality.

like image 74
Rob Kennedy Avatar answered Sep 21 '22 08:09

Rob Kennedy


In a word, no.

You can use something like InterlockedIncrement() depending on your platform. On .NET you can use the Interlocked class methods (Interlocked.Increment() for example).

A Rob Kennedy mentioned, even if the operation is implemented in terms of a single INC instruction, as far as the memory is concerned a read/increment/write set of steps is performed. There is the opportunity on a multi-processor system for corruption.

There's also the volatile issue, which would be a necessary part of making the operation thread-safe - however, marking the variable volatile is not sufficient to make it thread-safe. Use the interlocked support the platform provides.

This is true in general, and on x86/x64 platforms certainly.

like image 27
Michael Burr Avatar answered Sep 21 '22 08:09

Michael Burr