Multi-threaded Objective-C accessors: GCD vs locks

梦想的初衷 提交于 2019-12-03 12:42:39

Is this pattern potentially the recommended method of writing multithreaded accessors?

I guess you wrote that with a serial queue in mind, but there is no reason for it. Consider this:

dispatch_queue_t queue = dispatch_queue_create("com.example", DISPATCH_QUEUE_CONCURRENT);

// same thing as your example
- (NSString*)something {
    __block NSString *localSomething;
    dispatch_sync(queue, ^{
        localSomething = _something;
    });
    return localSomething;
}

- (void)setSomething:(NSString*)something {
    dispatch_barrier_async(queue, ^{
        _something = something;
    });
}

It reads concurrently but uses a dispatch barrier to disable concurrency while the write is happening. A big advantage of GCD is that allows concurrent reads instead locking the whole object like @property (atomic) does.

Both asyncs (dispatch_async, dispatch_barrier_async) are faster from the client point of view, but slower to execute than a sync because they have to copy the block, and having the block such a small task, the time it takes to copy becomes meaningful. I rather have the client returning fast, so I'm OK with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!