If you are using GCC 4.7, you can use the new Transactional Memory function to do the following:
Transactional memory is designed to simplify programming with threads, in particular, to synchronize access to data shared by multiple threads using transactions. As with the databases, a transaction is a unit of work that either completes completely or has no effect at all (i.e., transactions are performed atomically). In addition, transactions are isolated from each other, so that each transaction sees a consistent view of memory.
Currently, transactions are only supported in C ++ and C in the form of transaction statements, transaction expressions, and function transactions. In the following example, both a and b will be read, and the difference will be written to c, all atomically and isolated from other transactions:
__transaction_atomic { c = a - b; }
Therefore, another thread may use the following code to update b simultaneously, without forcing c to hold a negative value (and without the need to use other synchronization constructs, such as locks or C ++ 11 atoms):
__transaction_atomic { if (a > b) b++; }
The exact semantics of transactions are defined in terms of the C ++ 11 / C1X memory model (see the specification link below). Roughly speaking, transactions provide synchronization guarantees similar to those that would be guaranteed if a single global lock were used as protection for all transactions. Please note that, like other synchronization constructs in C / C ++, transactions rely on a program without taking into account the distribution (for example, writing without a transaction, which simultaneously with transactional reading to the same memory location, is a data consumption).
Additional information: http://gcc.gnu.org/wiki/TransactionalMemory