dispatch_barrier_async一些用法

- (NSDictionary *)HTTPRequestHeaders {
    NSDictionary __block *value;
    dispatch_sync(self.requestHeaderModificationQueue, ^{
        value = [NSDictionary dictionaryWithDictionary:self.mutableHTTPRequestHeaders];
    });
    return value;
}

- (void)setValue:(NSString *)value
forHTTPHeaderField:(NSString *)field
{
    dispatch_barrier_async(self.requestHeaderModificationQueue, ^{
        [self.mutableHTTPRequestHeaders setValue:value forKey:field];
    });
}

- (NSString *)valueForHTTPHeaderField:(NSString *)field {
    NSString __block *value;
    dispatch_sync(self.requestHeaderModificationQueue, ^{
        value = [self.mutableHTTPRequestHeaders valueForKey:field];
    });
    return value;
}


1、在AFNetworking中,dispatch_barrier_async用来保证写线程的安全性,;以上面self.mutableHTTPRequestHeader 为例,通过dispatch_barrier_async,能保证每次写self.mutableHTTPRequestHeader时,没有线程在读self.mutableHTTPRequestHeader;同时,写入self.mutableHTTPRequestHeader时是在子线程中写的

2、self.requestHeaderModificationQueue是一个并发队列,dispatch_sync(self.requestHeaderModificationQueue, 实现多线程读取同一个变量,又能保证同步获取到数据




你可能感兴趣的:(iOS)