gpt4 book ai didi

ios - 带有串行队列的 CMMotionManager

转载 作者:行者123 更新时间:2023-11-29 00:25:03 25 4
gpt4 key购买 nike

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

从日志中我可以看到两个 block 在不同的线程上执行,因为 NSMutableArray 不是线程安全的,而且我还修改了两个 block 中的数组,我操作这个数组是否安全怎么办?

我还读到串行队列上的任务一次执行一个,如果只监视两个 Action 之一,修改数组是否安全?

@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);
}];
}

}

最佳答案

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

如果您想加倍确定,可以在修改数组时锁定数组,方法是在 @synchronized block 内执行操作:

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

也就是说,我认为没有必要。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com