GCD 队列而不是锁:读取 Tableview 的 cellForRowAtIndexPath 数据

发布于 2024-10-08 12:29:19 字数 601 浏览 0 评论 0原文

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];
    });
}

当您有一个生产者线程一次添加大量推文(而不是一条一条)时,如何使用 GCD 处理锁和临界区,并且您需要一次阅读 UITableView 的 cellForRowAtIndexPath 的一条推文?

如果在每次“读​​取”时保持“同步”,是否会导致大量不必要的块?这确实是偶尔写一次,但经常读的场景。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南城旧梦 2024-10-15 12:29:19

如果延迟是一个问题,也许生产者应该一条一条地添加推文,以便 UI 线程的dispatch_sync 调用保持响应。

我不会担心“很多不必要的块”,除非/直到分析表明块调度开销实际上是一个问题。毕竟, cellForRowAtIndexPath 只会针对可见单元格调用,因此“经常读取”意味着每秒数十次,而不是数千或数百万次。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文