多线程同步问题中,读者——写者问题,iOS实现。

多线程同步问题中,读者——写者问题,iOS实现。


@interface AppDelegate () {
    dispatch_queue_t _resourceQueue;
    NSString* _resource;
}

@end

@implementation AppDelegate

- (NSString *)resource {
    __block id result = nil;
    dispatch_sync(_resourceQueue, ^() {
        result = _resource;
    });
    return result;
}
- (void)setResource:(NSString *)resource {
    dispatch_barrier_async(_resourceQueue, ^() {
        sleep(3.0f);
        _resource = resource;
    });
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    _resourceQueue = dispatch_queue_create("resourceQueue", DISPATCH_QUEUE_CONCURRENT);
    
    NSOperationQueue* queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:2];
    for (int i = 0; i < 50; i++) {
        if (arc4random() % 10 <= 1) {
            NSString* string = [NSString stringWithFormat:@"string %02d", i];
            [queue addOperationWithBlock:^() {
                [self setResource:string];
            }];
        } else {
            [queue addOperationWithBlock:^() {
                [self resource];
            }];
        }
    }
}

@end


你可能感兴趣的:(ios,Concurrent)