2017-04-05 60 views
0

我有一个串行队列以0.01秒为间隔同时接收陀螺仪和加速度计运动更新。带串行队列的CMMotionManager

从日志中我可以看到两个块在不同的线程上执行,因为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); 
     }]; 
    } 

} 

回答

1

是的,它应该是安全的。处理程序块将在您的NSOperationQueue上按顺序执行,因为您已设置maxConcurrentOperationCount = 1

如果你想以防万一,你可以修改它的时候,通过执行@synchronized块内的操作锁定阵列:

@synchronized(self.array) { 
    // Modify self.array here... 
} 

这么说,我不认为这是必要的。

+0

感谢您的回答,'@ synchronized'虽然有点贵。 – gabbler