Can an instance method of a class call another thread to use the properties of the class?

I've researched and debugged this issue in my application for several days, but I still can't get an answer. So I think it would be best to ask a question. And here we go ...

Suppose we are instantiating a class on the main thread, but place a call to one method of that class on another thread using dispatch_async. Will it be thread safe if this method uses properties in the class (the class is instantiated on the main thread. Of course, the access to properties will be pass-through.)? 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 have a recursive method in one of the classes in my application that accesses properties. It is just that this method is meant to be called on another thread so as not to block the UIKit thread. However, the memory only continues to climb at 30MB per second when the method is executed! I think it has something to do with leak and multithreading, but I cannot find a leak in the Tools. So I'm here to see if it's thread safe to access such properties.

I am sorry if my question is difficult to understand, I am not a native speaker :). Thanks for leaving.

+3


source to share


1 answer


In general, you only get thread safety if you use some kind of synchronization mechanism such as locks or barriers or sequential queues. It is possible that a simple data value would be safe without synchronization, but it is not, because the processor (compiler?) May decide to cache the values ​​rather than write them to memory right away.

Objects and streams are essentially unrelated concepts. Each method runs on a thread, but does not affect the threads where other methods run. This includes the constructor.



In situations like yours, using a named concurrent queue to access the c property dispatch_sync

to read from and dispatch_barrier_async

write to it is an attractive idea.

There is a good discussion here: https://www.mikeash.com/pyblog/friday-qa-2011-10-14-whats-new-in-gcd.html under the heading Custom Parallel Queues and Barriers.

+1


source







All Articles