线程、QRunnable 和 QThreadPool,我无法描述细节
我知道一般理论,Thread,QRunnable和QThreadPool。这一切是如何适应的?我的意思是,当创建 QRunnable 实例并将其分配给 ThreadPool 时,启动线程意味着什么?多个线程可以访问同一个 QRunnable 吗?一个 QRunnable 是否一定与一个工作线程一对一映射?
I know the general theory, Thread, QRunnable and QThreadPool. How does it all fit in ? I mean when an instance of QRunnable is created, and assigned to the ThreadPool, what does it mean to start a thread ? Can multiple threads access the same QRunnable ? Does one QRunnable necessarily map one-to-one with one worker thread ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
QRunnable 封装了您想要在单独的线程中执行的任务。如果您需要知道哪个线程正在运行该任务或在线程之间共享该任务,那么您可能正在做一些比 QThreadPool 的设计目的更复杂的事情。在这种情况下,您可以直接使用 QThread 创建自定义行为。使用 QThreadPool“启动”QRunnable 类似于将该任务排队以获取池中的可用线程。然而,启动 QThread 实际上会分配一个新的操作系统线程并执行它。
线程池将使用 QRunnable 实例的工作队列来管理有限数量的线程。当线程变得可用时,它将被分配一个 QRunnable 来处理。如果您将 QThreadPool 与 QRunnable 一起使用,则不需要显式创建任何 QThread 实例。请注意,在 QRunnable 实例中使用时,您仍然必须确保共享资源是同步的(例如,与 QMutex、QMutexLocker、QReadWriteLock、QSemaphore 和/或 QWaitCondition)。
QRunnable encapsulates a task that you want performed in a separate thread. If you need to know which thread is running that task or share it between threads, then you are probably doing something more complicated than what QThreadPool is designed to empower. In that case, you would create custom behavior using QThread directly. "Starting" a QRunnable with a QThreadPool is analogous to queueing that task for an available thread in the pool. Whereas, starting a QThread actually allocates a new OS thread and executes it.
The thread pool will manage a finite number of threads with a work queue of QRunnable instances. As a thread becomes available, it will be assigned a QRunnable to process. You don't need to explicitly create any QThread instances if you are using QThreadPool with QRunnable. Note that you still must ensure that shared resources are synchronized (e.g. with a QMutex, QMutexLocker, QReadWriteLock, QSemaphore, and/or QWaitCondition) when used in QRunnable instances.