0

Thread safety is a state where your code behave correctly in multithread environment and always return valid value under multiple read and write operations, and atomic property is also state that it will always give some valid value. So why is it not thread safe?

Rob
  • 371,891
  • 67
  • 713
  • 902
  • 1
    When dealing with objects, atomic only ensures that the access to the pointer, itself, is thread safe, but not that mutations/operations of the object in question are thread safe. E.g. consider pointer to an array. Sure, with `atomic` you ensure that references to the pointer are OK, but not that the list of items isn’t mutating contained with that array aren’t changing as your thread might be iterating through the list. In short, atomic is generally insufficient to achieve thread safety. – Rob May 06 '19 at 15:49
  • See https://stackoverflow.com/a/40514368/1271826, which references [Programming with Objective-C: Encapsulating Data](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/EncapsulatingData/EncapsulatingData.html#//apple_ref/doc/uid/TP40011210-CH5-SW37) which tells us “Property atomicity is not synonymous with an object’s thread safety." – Rob May 06 '19 at 15:53
  • Also see bbum’s [Objective-C: Atomic, properties, threading and/or custom setter/getter](http://www.friday.com/bbum/2008/01/13/objectivce-c-atomic-properties-threading-andor-custom-settergetter/). – Rob May 06 '19 at 15:55
  • Just in case the answers on the "duplicate" questions don't help you: The most important part of "thread safety" is preserving _relationships_ between different variables. A single atomic variable always is thread safe, but if some algorithm uses _several_ variables, you can't make the whole algorithm thread safe just by making each of the variables individually thread safe. You need to use locks to prevent threads B, C, and D from seeing the variables _as a group_ while thread A is in the middle of changing them one-by-one. – Solomon Slow May 08 '19 at 13:50

0 Answers0