C++ multithreading problem - is mutex the only way?

c++, java, multithreading, synchronization

Solution

Most processors have 'atomic' increment and decrement instructions - in a large part, they are how mutexes are implemented at a machine level.

You can access these atomic instructions in your own code. Windows provides the `InterlockedIncrement()` function, and glib provides equivalents. In x86 assembly language, you can use `LOCK CMPXCHG` and kin directly.

C++ does not know anything about these concepts - you must use them yourself; there are no magic keywords for thread safety in C++.

See Atomic Instruction

Problem

I have a counter variable which will be accessed by multiple threads which will increment/decrement it. It should not be updated by multiple threads at the same time. I know that you can create a mutex object which has to be obtained before the variable in question can be changed. A critical section in this case is not appropriate because there are more than 1 function which can change the variable in question. Is there another I can do this without using the mutex? Using a mutex does have a performance penalty (see http://www.codeguru.com/forum/showthread.php?t=333192). I believe that in Java, there is a key word you can use in the variable declaration to accomplish that (is it called "synchronized"?), but is there such a thing in C++ at all? I know that volatile is not the keyword I am looking for. Thank you very much.

Original source

Related problems