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