views:

1694

answers:

7

In a C++ Linux app, what is the simplest way to get the functionality that the Interlocked functions on Win32 provide? Specifically, a lightweight way to atomically increment or add 32 or 64 bit integers?

A: 

Upon further review, this looks promising. Yay stack overflow.

twk
+4  A: 

Intel's open-source ThreadBuildingBlocks has a template, Atomic, that offers the same functionality as .NET's Interlocked class.

Unlike gcc's Atomic built-ins, it's cross platform and doesn't depend on a particular compiler. As Nemanja Trifunovic correctly points out above, it does depend on the compare-and-swap CPU instruction provided by x86 and Itanium chips. I guess you wouldn't expect anything else from an Intel library : )

cero
+3  A: 

Strictly speaking, Linux cannot offer atomic "interlocked" functions like ones in Win32, simply because these functions require hardware support, and Linux runs on some platforms that don't offer that support. Having said that, if you can constrain yourself to Intel x68/x64, take a look at the implementation of reference counting in Boost shared pointers library.

Nemanja Trifunovic
+4  A: 

Just few notes to clarify the issue which has nothing to do with Linux.

RWM (read-modify-write) operations and those that do not execute in a single-step need the hardware-support to execute atomically; among them increments and decrements, fetch_and_add, etc.

For some architecture (including I386, AMD_64 and IA64) gcc has a built-in support for atomic memory access, therefore no external libray is required. Here you can read some information about the API.

Nicola Bonelli
+2  A: 

The atomic functions from the Apache Portable Runtime are really close to the Win32 InterlockedXXX functions.

Clay
+1  A: 

You can insert some assembly code in your source, to use x68 interlocked instructions directly.

You should use a lock xadd operation.

See for instance this.

+1  A: 

The fairly common glib library that's used in GTK and QT programming as well as standalone offers a variety of atomic operations. See http://library.gnome.org/devel/glib/2.16/glib-Atomic-Operations.html for a list. There are g_atomic functions for most of the operations that Interlocked supports on Win32, and on platforms where the hardware directly supports these, they are inlined as the needed assembly code.

Ben Combee