2017-04-05 42 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