In my Cocoa/iOS application I have a static double variable (let's call it foo) which must be:
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 …
foo after it is written on the background thread (given that foo is declared volatile)? IOW, Have I done enough to ensure that the two threads will see the result each other's read/write operations?volatile for a double value is faster/more-lightweight/preferable in this situation rather than a mutex lock like an @synchronized block or an NSLock. Is that true? IOW, is volatile the best solution for this particular case?1) No. volatile is not a substitute for an atomic primitive here. Close, but not quite.
2) Problem with volatile is, it's not correct, as you now know.
Ideal: You may have access to the latest atomic language features, such as _Atomic for 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 simple pthread_mutex_t or 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With