我有一个串行队列,以0.01秒的间隔接收陀螺仪和加速计的运动更新。
从日志中我可以看到两个块在不同的线程上执行,因为NSMutableArray不是线程安全的,而且我还修改了这两个块中的数组,这样对我来说操作数组是安全的吗?
我还读到,串行队列上的任务一次执行一个,如果只监视两个运动中的一个,那么修改数组是否安全?
@implementation NSThread (GetSequenceNumber)
- (NSInteger)number
{
return [[self valueForKeyPath:@"private.seqNum"] integerValue];
}
@end
@interface SensorCollector()
@property (nonatomic, strong) NSMutableArray *array;
@end
@implementation SensorCollector
- (id)init {
if (self = [super init]) {
self.motionManager = [CMMotionManager new];
self.queue = [[NSOperationQueue alloc] init];
self.queue.maxConcurrentOperationCount = 1;
_array = [NSMutableArray array];
}
return self;
}
- (void)starCollect {
float updateInterval = 0.01;//50Hz
//setup sensors callback in background NSOperationQueue
if ([self.motionManager isAccelerometerAvailable]) {
[self.motionManager setAccelerometerUpdateInterval:updateInterval];
[self.motionManager startAccelerometerUpdatesToQueue:self.queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
//modify self.array here
NSLog(@"Acce %ld", [NSThread currentThread].number);
}];
}
if ([self.motionManager isGyroAvailable]) {
[self.motionManager setGyroUpdateInterval:updateInterval];
[self.motionManager startGyroUpdatesToQueue:self.queue withHandler:^(CMGyroData *gyroData, NSError *error) {
//also modify self.array here
NSLog(@"Gyro %ld", [NSThread currentThread].number);
}];
}
}发布于 2017-04-05 23:33:39
是的,应该是安全的。由于您设置了maxConcurrentOperationCount = 1,处理程序块将在您的NSOperationQueue上按顺序执行。
如果您想要加倍确定,可以在修改数组时锁定它,方法是在@synchronized块中执行以下操作:
@synchronized(self.array) {
// Modify self.array here...
}也就是说,我不认为这是必要的。
https://stackoverflow.com/questions/43235007
复制相似问题