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);
}];
}
}
感謝您的回答,'@ synchronized'雖然有點貴。 – gabbler