문제

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 NSArray *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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top