I could not find any examples how to deal with the same (class) variable when operation queue is used. In C & threads its about mutexes. So, what happens when NSOperationQueue
starts a thread for operation and class variable is modified? Is it thread safe? Thank you.
@interface MyTest {
NSMutableArray *_array;
}
@end
-(id)init
{
...
_array = [NSMutableArray new]; // class variable
// queue time consuming loading
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation =
[NSInvocationOperation initWithTarget:self
selector:@selector(populate)
object:nil];
[queue addOperation:operation];
// start continuous processing
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(processing)
userInfo:nil
repeats:YES];
...
}
-(void)populate
{
while (...)
{
id element = ...; // time consuming
// modify class variable "_array" from operation's thread (?)
[_array addObject:element];
// Ok, I can do instead of addObject
// performSelectorOnMainThread:withObject:waitUntilDone:
// but is it the only way? Is it needed?
}
}
// access and/or modify class variable "_array"
-(void)processing
{
NSLog(@"array.count = %d", array.count);
for (id i in _array)
{
[_array addObject:[NSNumber numberWithInt:rand() % 100]];
// etc...
}
}