我有一个ObjC类(Writer),它有一些属性,并在主线程上写入这些属性。然后还有其他类(Reader)在主线程或后台线程上读取这些属性。
当读者从主线程中读取时,它会在Writer类中保存这些属性的确切值,但是当读者从后台线程中读取时,显然没有保证读者会得到相同的值。这是示例代码。
这里是Writer类
在Reader课程中:
我想确保numberSum确实是所有人的总和 numberString变量。
// Writer Class
@interface Writer : NSObject
@property (nonatomic,strong) NSString* numberString;
@property (nonatomic,assign) NSUInteger numberSum;
@end
@implementation Writer
-(instancetype)init {
if (self = [super init]){
self.numberString = @"1";
self.numberSum = 1;
self.timer = [NSTimer timerWithTimeInterval:0.1f target:self selector:@selector(writeToVariables:) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
return self;
}
- (void)writeToVariables:(NSTimer *)timer {
self.numberString = [self.numberString stringByAppendingString:@",1"];
self.numberSum += 1;
}
// Reader Class
@interface Reader ()
@property (nonatomic,strong) Writer* writer;
@end
@implementation Reader
-(instancetype)init {
if (self = [super init]){
self.writer = [Writer new];
}
return self;
}
-(void) getVariablesOnBackground:(BOOL)background {
void (^readerBlock)() = ^{
NSString* numberStr = self.writer.numberString;
// Introduce delay So background thread get time to update numberSum
int i=0;
while (i < 10000000) {
i += 1;
}
NSUInteger numberSum = self.writer.numberSum;
NSArray *onesArray = [numberStr componentsSeparatedByString:@","];
NSLog(@"%lu",(unsigned long)onesArray.count);
NSLog(@"%lu",(unsigned long)numberSum);
};
// If background then dispatch on default queue else just call the block
if (background) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),readerBlock);
}
else {
readerBlock();
}
}
@end
这是演示代码,仅用于示例目的。当在主线程中执行时,readerBlock中的两个NSLog语句将始终打印相同,但是在后台线程中它们将在某个时间不同,因为在读取numberString之后读取numberString时读取它的时间已经由Writer中的主线程更新。
我应该怎样做以确保无论调用线程如何都能获得正确的值?
答案 0 :(得分:1)
您需要的是并发调度队列和调度屏障功能的组合。只要您需要同时访问numberString
和numberSum
,您应该隐藏它并提供单一方法来同时获取它们。喜欢这个
@interface Writer : NSObject {
NSString* numberString;
NSUInteger numberSum;
dispatch_queue_t accessQueue;
}
- (NSDicionary*) readStringAndSum;
@end
@implementation Writer
- (instancetype) init {
...
accessQueue = dispatch_queue_create("Access queue", DISPATCH_QUEUE_CONCURRENT);
...
}
- (void)writeToVariables:(NSTimer *)timer {
dispatch_barrier_async(accessQueue, ^{
numberString = [self.numberString stringByAppendingString:@",1"];
numberSum += 1;
});
}
- (NSDicionary*) readStringAndSum; {
__block NSDictionary* response;
dispatch_sync(accessQueue ^{
response = @{@"Sum" : [NSNumber numberWithUnsignedInteger: numberSum],
@"String" : [numberString copy];
}
});
return response;
}
@end