mikeash.com pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html commentshttp://www.mikeash.com/?page=pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html#commentsmikeash.com Recent CommentsThu, 28 Mar 2024 10:47:11 GMTPyRSS2Gen-1.0.0http://blogs.law.harvard.edu/tech/rssmikeash - 2010-12-18 02:13:22http://www.mikeash.com/?page=pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html#commentsThe getter needs to be synchronized because <code>[_foo retain]</code> is not an atomic operation. It's split into two steps: retrieving the value of <code>_foo</code>, and then sending retain to it. If the setter were to run in between those two steps, the <code>retain</code> would be sent to a dangling pointer and can crash.ae730ae83002d8a5476e425ee033c070Sat, 18 Dec 2010 02:13:22 GMTTommy - 2010-12-18 01:47:28http://www.mikeash.com/?page=pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html#commentsIn the thread safe accessor section, why is the synchronize call necessary in the getter function?e07a864d5dee7f76d7f9eb7d68d45865Sat, 18 Dec 2010 01:47:28 GMTfoobaz - 2010-12-04 22:48:05http://www.mikeash.com/?page=pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html#commentsI wish -[NSDictionary objectForKey:] returned a retained+autoreleased object, to avoid the bug in your first example. Most Cocoa methods return autoreleased objects, so this behavior would be more consistent.55ec4af94312a0632b9d35f2e2c89e6cSat, 04 Dec 2010 22:48:05 GMTmikeash - 2010-12-03 22:29:38http://www.mikeash.com/?page=pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html#commentsYes, that's exactly right. Imagine this sequence of events: <br /><code> <br />// thread 1 <br />[_foo release]; <br /> <br />// thread 2 <br />id foo = [obj foo] <br /> <br />// thread 1 <br />_foo = [newFoo retain]; <br /></code> <br />Thread 2 ends up with a reference to a released, potentially destroyed object.914520d8cce0271cce7e3e1f8b8fb1d7Fri, 03 Dec 2010 22:29:38 GMTBrian - 2010-12-03 21:35:03http://www.mikeash.com/?page=pyblog/friday-qa-2010-12-03-accessors-memory-management-and-thread-safety.html#commentsIn the section where you use the Person object, you mention that your first example that @synchronized would keep the code from crashing. Can you please explain why it would crash without it? Would it be when a thread uses the getter in between another thread calling release and assigning the new value? Thanks for all the great info.915fa7b2cd6441b565de74c9ed1fbf7fFri, 03 Dec 2010 21:35:03 GMT