Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Thread Safe Integer

I have currently created a C++ class for a thread safe integer which simply stores an integer privately and has public get a set functions which use a boost::mutex to ensure that only one change at a time can be applied to the integer.

Is this the most efficient way to do it, I have been informed that mutexes are quite resource intensive? The class is used a lot, very rapidly so it could well be a bottleneck...

Googleing C++ Thread Safe Integer returns unclear views and oppinions on the thread safety of integer operations on different architectures.

Some say that a 32bit int on a 32bit arch is safe, but 64 on 32 isn't due to 'alignment' Others say it is compiler/OS specific (which I don't doubt).

I am using Ubuntu 9.10 on 32 bit machines, some have dual cores and so threads may be executed simultaneously on different cores in some cases and I am using GCC 4.4's g++ compiler.

Thanks in advance...

Please Note: The answer I have marked as 'correct' was most suitable for my problem - however there are some excellent points made in the other answers and they are all worth reading!

like image 345
Paul Ridgway Avatar asked Apr 28 '10 12:04

Paul Ridgway


People also ask

Is an integer thread safe?

No, absolutely not. The spec is extremely clear on this point: Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.

Is ++ thread safe in C?

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

Is C write thread safe?

write() is certainly thread-safe. The problem is that a partial write() could require multiple calls in order to completely write the data, and while that is "thread-safe" it could result in interleaved data.

Is printf () thread safe?

the standard C printf() and scanf() functions use stdio so they are thread-safe.


1 Answers

There is the C++0x atomic library, and there is also a Boost.Atomic library under development that use lock free techniques.

like image 186
Vicente Botet Escriba Avatar answered Sep 29 '22 12:09

Vicente Botet Escriba