Reputation: 1188
I have been researching and debugging this problem in my app for days, but I still can't get an answer. So I think it would be best to just ask the question. And here we go...
Suppose that we create an instance of a class on the main thread, but place the call of one method of that class on a different thread using dispatch_async. Would it be thread-safe if that method uses properties in the class (The class instance is created on the main thread. Surely accessing the properties would be cross-thread.)? An example would be:
@interface AClass
@property (nonatomic) int blah; //Would it be more thread-safe if it is "atomic" instead?
- (void)foo;
@end
//Method implementation
- (void)foo {
self.blah++;
}
//dispatch_async on main thread
dispatch_async(dispatch_get_global_queue(...PRIORITY_BACKGROUND, 0), ^{
[aClassInstance foo];
});
I do have a recursive method in one of the classes in my app that accesses properties. It's only that that method is meant to be called on a different thread, so not to block the UIKit thread. However, the memory just keeps climbing at 30MB per second when the method is executing! I think this has something to do with a leak and multi-threading, but I cannot seem to find the leak in Instruments. So I am here to ask if it is thread-safe to access properties like this.
I'm sorry if my question is hard to understand, I am not a native speaker :). Thanks for dropping in.
Upvotes: 3
Views: 384
Reputation: 31016
In the general case, you only get thread safety if you use some synchronization mechanism such as locks, or barriers, or serial queues. It's possible that a simple data value will be safe without synchronization but that's not certain either because the processor (compiler?) may decide to cache values rather than immediately write them to memory.
Objects and threads are essentially unrelated concepts. Each method executes on some thread but that has no influence on the threads where other methods execute. That includes the constructor.
For situations such as yours, using a named concurrent queue for access to the property with dispatch_sync
to read from it and dispatch_barrier_async
to write to it is an appealing idea.
There's a good discussion here: https://www.mikeash.com/pyblog/friday-qa-2011-10-14-whats-new-in-gcd.html under the heading "Custom Concurrent Queues and Barriers".
Upvotes: 1