我有一个串行队列,以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);
        }];
    }

}

最佳答案

是的,应该很安全。由于已设置NSOperationQueue,因此将在maxConcurrentOperationCount = 1上顺序执行处理程序块。

如果您想双重确定,可以在修改数组时通过在@synchronized块内执行操作来锁定数组:

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


就是说,我认为这不是必需的。

关于ios - 带有串行队列的CMMotionManager,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43235007/

10-08 23:47