dispatch_sync&dispatch_barrier_async 实现同步

//queue 为全局串行队列
_queue = dispatch_queue_create("cocoa.lumberjack.multiformatter", NULL);
//读取操作使用dispatch_sync
- (NSArray *)formatters {
    __block NSArray *formatters;

    dispatch_sync(_queue, ^{
        formatters = [_formatters copy];
    });

    return formatters;
}
//写入或更改操作使用 dispatch_barrier_async
- (void)addFormatter:(id)formatter {
    dispatch_barrier_async(_queue, ^{
        [_formatters addObject:formatter];
    });
}

- (void)removeFormatter:(id)formatter {
    dispatch_barrier_async(_queue, ^{
        [_formatters removeObject:formatter];
    });
}

- (void)removeAllFormatters {
    dispatch_barrier_async(_queue, ^{
        [_formatters removeAllObjects];
    });
}
//在项目最后要记得释放创建的queue
- (void)dealloc {
    dispatch_release(_queue);
}

你可能感兴趣的:(dispatch_sync&dispatch_barrier_async 实现同步)