我正在处理一些不在主线程上完成的音频处理。我的后台线程反复生成浮动数组,我的主线程将使用这些浮动数组向用户显示某些内容。这会是线程安全的还是过于简单化了?由于这是在 OpenGL 循环中,因此我想避免使用atomic
锁定阻塞任一线程。
我对存储格式很灵活。(C 数组、NSArray 等和 double、CGFloat、NSNumber 等)
请注意,每次调用第二种方法时,它可能有也可能没有要处理的实际新数据。它只想要最新的东西。
@interface
@property (nonatomic, strong) NSMutableArray *generatedNumbers;
@property (nonatomic, strong) NSArray *passedNumbers;
...
@end
@implementation
//This is called over and over repeatedly and an unpredictable rate
- (void) generateSomeNumbers{
...
[self.generatedNumbers removeAllObjects];
for (Something x in something){
...
[self.generatedNumbers addObject:someNSNumberOrCGFloat];
}
}
//This is called from the main thread (opengl CADisplayLink)
- (void) doStuffWithLatestGeneratedNumbers{
self.passedNumbers = [NSArray arrayWithArray:self.generatedNumbers];
[self doStuffWithNumbers:self.passedNumbers];
}
或者这个怎么样?:
@interface
@property (nonatomic, strong) NSMutableArray *generatedNumbers;
@property (nonatomic, strong) NSArray *passedNumbers;
...
@end
@implementation
//This is called over and over repeatedly and an unpredictable rate
- (void) generateSomeNumbers{
...
[self.generatedNumbers removeAllObjects];
for (Something x in something){
...
[self.generatedNumbers addObject:someNSNumberOrCGFloat];
}
[self copyNumbers:self.generatedNumbers];
}
- (void)copyNumbers:(NSArray *)numbers
{
@autoreleasepool
{
dispatch_async(dispatch_get_main_queue(), ^{
self.passedNumbers = [NSArray arrayWithArray:self.generatedNumbers];
});
}
}
//This is called from the main thread (opengl CADisplayLink)
- (void) doStuffWithLatestGeneratedNumbers{
[self doStuffWithNumbers:self.passedNumbers];
}