In my Cocoa/iOS application I have a static double variable (let’s call it foo) which must be:
- updated by one part of my app on a background thread
- read by another part of my app on the main thread
I’m looking for the most lightweight way to synchronize access to foo.
Note: I know that the simplest solution in these cases is usually to adjust the code such that only one thread accesses the variable, and therefore no synchronization is necessary. Let’s assume that I have determined that restricting foo access to a single thread is not possible in this case (maybe the action taken in step 1 occurs so rapidly/often that thread switching is not desirable). Please do not respond with an answer of “restrict foo access to one thread”. I am looking for alternatives to that.
My current understanding is that using a volatile variable is the most lightweight way to synchronize access to foo. So foo is declared something like this:
static volatile double foo = 60.0;
Background thread writing code is something like:
foo = 90.0;
Main thread reading code is something like:
double bar = 0.0;
bar = foo;
// use bar here …
Some questions:
- Is the main thread guaranteed to see the updated value of
fooafter it is written on the background thread (given thatfoois declaredvolatile)? IOW, Have I done enough to ensure that the two threads will see the result each other’s read/write operations? - I’m assuming that using
volatilefor adoublevalue is faster/more-lightweight/preferable in this situation rather than a mutex lock like an@synchronizedblock or anNSLock. Is that true? IOW, isvolatilethe best solution for this particular case?
1) No.
volatileis not a substitute for an atomic primitive here. Close, but not quite.2) Problem with
volatileis, it’s not correct, as you now know.Ideal: You may have access to the latest atomic language features, such as
_Atomicfor C11 and/or<atomic>in C++11.If not, then you could either use a 64 bit integer and atomic functions, which you read by value, then transfer to a
double, or you could use a simplepthread_mutex_tor perhaps even a spin lock (be very careful with spin locks).However… it may be better if you simply post changes to the value to the main thread’s run loop, if that is an option.