Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interlocked equivalent on Linux

Tags:

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?

like image 720
twk Avatar asked Sep 29 '08 17:09

twk


2 Answers

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 : )

like image 197
cero Avatar answered Nov 23 '22 16:11

cero


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.

like image 32
Nicola Bonelli Avatar answered Nov 23 '22 14:11

Nicola Bonelli