Multi-threaded Objective-C accessors: GCD vs locks

后端 未结 1 1624
难免孤独
难免孤独 2021-02-15 15:46

I\'m debating whether or not to move to a GCD-based pattern for multi-threaded accessors. I\'ve been using custom lock-based synchronization in accessors for years, but I\'ve f

1条回答
  •  悲&欢浪女
    2021-02-15 16:26

    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.

    0 讨论(0)
提交回复
热议问题