开发者

GCD Queues instead of locks: reading data for Tableview's cellForRowAtIndexPath

开发者 https://www.devze.com 2023-01-31 01:31 出处:网络
One Apple\'s site, there\'s suggested pattern for using GCD queues instead of locks: // Create queue early

One Apple's site, there's suggested pattern for using GCD queues instead of locks:

// Create queue early
queue = dispatch_queue_create("com.example.tweets", NULL);

// executed main thread
- (NSArray *)getTweets
{
    __block NSAr开发者_运维百科ray *a;
    dispatch_sync(queue, ^{
        a = [tweets copyTweets];
    });

    return a;
}

// executed on background thread
- (void)addTweet:(Tweet *)tw
{
    dispatch_async(queue, ^{
        [tweets addTweet:tw];
    });
}

How do you deal with the locks and critical sections with GCD when you have a producer thread adding a lot of tweets at once, instead of one by one and you need to read one tweet at a time for UITableView's cellForRowAtIndexPath?

If you kept the 'sync' on each 'read', won't that cause a lot of unnecessary blocks? This is really write once in a while, but read often scenario..


If latency is a concern, maybe the producer should add tweets one-by-one, so the dispatch_sync calls from the UI thread remain responsive.

I would not worry about "a lot of unnecessary blocks" unless/until profiling shows that the block dispatch overhead is actually an issue. After all, cellForRowAtIndexPath is only going to be called for visible cells, so "read often" means something like dozens of times a second, not thousands or millions.

0

精彩评论

暂无评论...
验证码 换一张
取 消