线程安全:NSOperationQueue +

在使用操作队列时,找不到任何示例如何处理同一个(类)variables。 在C&线程关于互斥体。 那么,当NSOperationQueue启动一个线程的操作和类variables会发生什么变化呢? 线程安全吗? 谢谢。

 @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... } } 

不,这是不是线程安全的,如果你启动一个线程,对一个类variables做一些工作,可以由其他线程修改,那么它不是线程安全的,如果处理是从某个线程调用,而填充运行在另一个然后你当foreach循环看到数组已经被修改时,可能会得到一个exception,不过当你在你的例子中修改foreach循环内的数组时,你会得到这个exception(你不应该这样做,程序会抛出一个exception) …解决这个问题的一种方法是使用数组上的同步块,这将确保同步块不会同时执行,例如线程阻塞,直到一个同步块完成为止

  -(void)populate { while (...) { id element = ...; // time consuming // modify class variable "_array" from operation's thread (?) @synchronized(_array) { [_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 { @synchronized(_array) { NSLog(@"array.count = %d", array.count); for (id i in _array) { //you shouldnt modify the _array here you will get an exception // etc... } } }