一个 Apple 的网站,有使用 GCD 队列而不是锁的建议模式:
// 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];
});
}
当您有一个生产者线程一次添加大量推文而不是一一添加并且您需要一次读取一条推文以获取 UITableView 的 cellForRowAtIndexPath 时,您如何使用 GCD 处理锁和临界区?
如果您在每次“读取”时都保持“同步”,那不会导致很多不必要的阻塞吗?这真的是偶尔写一次,但经常读的场景..