Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread-safe retain/release

I have a class that is accessed from multiple background threads, potentially at the same time. I cannot copy the class because it's contents is potentially expensive to recreate (processing or memory-wise).

It is also possible that a property of this class is replaced while processing in the background is still going on and accessing this property.

At present I have regular retain/releases but it seems to be the case (at least on iOS 4) that these are not thread-safe because even though they are perfectly pairs it apparently occurs that the retainCount drops randomly and eventually this class gets deallocated.

I'm looking for suggestions on how to make this class thread-safe, permit concurrent access of properties and permit for a property to be modified while an "earlier version" of the property is still held onto by one of the background actions.

like image 947
Cocoanetics Avatar asked Oct 26 '25 03:10

Cocoanetics


1 Answers

Retain and release are atomic. Autorelease is not. Think of retains as per-thread; if thread A is holding a retain (or a retain/autorelease), then thread A's reference will be valid until that retain is balanced (or the autorelease pool is drained).

Autorelease can never be used as a cross-thread ownership transfer primitive.

Beyond that, hard to say what is going wrong in your app without more code.

like image 134
bbum Avatar answered Oct 28 '25 17:10

bbum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!