Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the volatile keyword necessary for an atomic property?

My class has a property:

@property (readwrite, atomic) BOOL IsTrue;

My understanding of the atomic qualifier is that the @synthesized getter/setter for the property will guarantee serialisation of access from different threads, i.e. if producer thread A is setting the property value it will be allowed to complete the set operation before consumer threads B and C are allowed to get the property value (as an aside here, is atomic even necessary for a single byte/POD type?).

Does the volatile keyword provide any further data integrity?

@property (readwrite, atomic) volatile BOOL IsTrue;

What I'm specifically driving at is that is there the possibility of consumer threads getting out-of-date values without the use of volatile?

like image 248
sam-w Avatar asked Feb 18 '23 14:02

sam-w


1 Answers

is there the possibility of consumer threads getting out-of-date values without the use of volatile?

No. From a client's point of view, the property is just a getter/setter method pair. So any client needs to call objc_msgSend to set or retrieve a value. Function calls are synchronization points in C so there's no way of getting out of date values (as with direct memory access, where volatile might be helpful).

The @synthesize'd accessors will take care of serializing access to the underlying value.

like image 176
Nikolai Ruhe Avatar answered Mar 04 '23 07:03

Nikolai Ruhe