Alex Rivera | Logout

C++ Thread Safe Integer

Asked 2010-04-28T12:43:41.307
17

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!

Edit
Report

1 Answer

1
answered 2010-04-28T16:19:45.257

Your Answer