gpt4 book ai didi

multithreading - 在 GCD(大中央调度)中创建 dispatch_queues 多少是太多了?

转载 作者:行者123 更新时间:2023-12-03 12:43:39 25 4
gpt4 key购买 nike

Mike Ash 有一篇关于 Swift 中构建的轻量级通知系统的精彩文章:(https://www.mikeash.com/pyblog/friday-qa-2015-01-23-lets-build-swift-notifications.html)。

基本思想是您创建可以“收听”的对象,即在发生某些状态更改时调用回调。为了使其线程安全,创建的每个对象都拥有自己的 dispatch_queue。 dispatch_queue 仅用于门控关键部分:

dispatch_sync(self.myQueue) {
// modify critical state in self
}

而且它很可能不会引起激烈的争论。我有点惊讶于你创建的每一个可以被监听的对象都创建了自己的调度队列,只是为了锁定几行代码。

一位发帖人建议使用 OS_SPINLOCK 会更快、更便宜;也许吧,但它肯定会使用更少的空间。

如果我的程序创建了数百或数千(甚至数万个对象),我应该担心创建这么多调度队列吗?可能大多数人甚至都不会被倾听,但有些人可能会。

两个对象不相互阻塞当然是有道理的,即有单独的锁,通常我不会三思而后行,比如在每个对象中嵌入一个 pthread_mutex ,而是一个完整的调度队列?真的可以吗?

最佳答案

Well, the documentation on Grand Central Dispatch关于调度队列的内部工作和确切成本相当模糊,但它确实指出:

GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects. Blocks submitted to dispatch queues are executed on a pool of threads fully managed by the system.



因此,听起来队列只不过是通过线程池对 block 进行排队的接口(interface),因此在空闲时对性能没有/最小的影响。

The conceptual documentation also states that:

You can create as many serial queues as you need



这听起来绝对像是创建串行调度队列并让它闲置的成本几乎是微不足道的。

此外,我决定在一个包含一些 Open GL 内容的应用程序上测试创建 10,000 个串行和并发调度队列,并没有发现性能受到任何影响,FPS 保持不变,并且只使用了额外的 4MB RAM(单个队列约 400 字节)。

在使用 OS_SPINLOCK 而不是调度队列方面,Apple 在其关于 migrating away threads 的文档中非常清楚。 GCD 比使用标准锁更有效(至少在竞争情况下)。

Replacing your lock-based code with queues eliminates many of the penalties associated with locks and also simplifies your remaining code. Instead of using a lock to protect a shared resource, you can instead create a queue to serialize the tasks that access that resource. Queues do not impose the same penalties as locks. For example, queueing a task does not require trapping into the kernel to acquire a mutex.



尽管还值得注意的是,如果您不使用队列,则始终可以释放它,并在以后需要再次使用时重新创建它,如果您担心内存。

TL;博士

调度队列是要走的路。您不必太担心创建大量队列而不使用它们,它们肯定比锁更有效。

编辑:您实际上发现自旋锁在非竞争情况下更快,因此您可能希望为此使用它!

关于multithreading - 在 GCD(大中央调度)中创建 dispatch_queues 多少是太多了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34980308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com