OGeek|极客世界-中国程序员成长平台

标题: ios - GCD为什么在我读取共享资源时使用dispatch_sync [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 14:32
标题: ios - GCD为什么在我读取共享资源时使用dispatch_sync

当我阅读共享资源时,我对使用 dispatch_sync 有一些疑问。 我在 Stack Overflow 上搜索了几个问题(如:GCD dispatch_barrier or dispatch_sync?),但没有找到确切的答案。

我不明白为什么要使用

- (void)addPhotoPhoto *)photo
{
     if (photo) { // 1
        dispatch_barrier_async(self.concurrentPhotoQueue, ^{ // 2 
            [_photosArray addObject:photo]; // 3
            dispatch_async(dispatch_get_main_queue(), ^{ // 4
                [self postContentAddedNotification]; 
            });
        });
     }
}

- (NSArray *)photos
{
    __block NSArray *array; // 1
    dispatch_sync(self.concurrentPhotoQueue, ^{ // 2
        array = [NSArray arrayWithArray:_photosArray];
    });
    return array;
}

我知道为什么要使用dispatch_barrier_async,但是我不知道为什么在阅读_photosArray的时候使用dispatch_sync,我猜_photosArray<的写操作self.concurrentPhotoQueue中,所以_photosArray的读取操作也需要在self.concurrentPhotoQueue中,否则使用 dispatch_sync 为了实现多读?

如果我在读操作时不使用dispatch_sync会怎样?如:

- (NSArray *)photos
{
    __block NSArray *array;
    array = [NSArray arrayWithArray:_photosArray];
    return array;
}

非常感谢!



Best Answer-推荐答案


可能 concurrentPhotoQueue 是一个串行队列。 concurrentPhotoQueue主要是为了同步访问photos数组。

由于它是串行的,因此来自该队列的所有访问都被序列化,如果您的应用中没有来自其他队列/线程的访问,则不会发生竞争条件。

写入访问可能是异步的,因为写入者通常不需要写入操作的结果。但是读取必须同步完成,因为调用者必须等待结果。如果您的 photos 方法将使用 dispatch_async 它会将结果写入 array after photos 方法已返回。因此,photos 总是会返回 nil

您的 photos 的非同步版本可能会产生竞争条件:_photosArray 可以在复制其内容时被修改,例如复制项目的数量和长度数组不同。这可能会导致 arrayWithArray: 内部崩溃。

关于ios - GCD为什么在我读取共享资源时使用dispatch_sync,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48727343/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4