QThread threadpool
QThread threadpool
本文关键字:threadpool QThread 更新时间:2023-10-16
我正在尝试使用 QThread 编写线程轮询。
class ThreadPool: public QObject
{
Q_OBJECT
public:
ThreadPool(int maxThreads);
void addTask(MyTask *task);
private:
int maxThreads;
QMutex mutex;
QVector<QPair<bool, QThread>> threads;
QThread *getFreeThread();
public slots:
void freeThread();
};
void ThreadPool::addTask(MyTask* task)
{
QThread *thread = getFreeThread();
task->moveToThread(thread);
connect(thread, SIGNAL(started()), task, SLOT(doWork()));
connect(task, SIGNAL(workFinished()), thread, SLOT(quit()));
connect(thread, SIGNAL(finished()), task, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), this, SLOT(freeThread()));
thread->start();
}
我正在创建有限数量的线程,我想在其中执行任务。但是,我不明白如何获取释放线程的编号。我知道QThreadPool和Qtconcurrent,但我不想使用它。也许,值得注意的是 QPair 向量中的每个线程是否免费。
-
您实际上并不需要
QVector<QPair<bool, QThread>>
来跟踪池中的所有线程,而是使用仅包含指向空闲线程的指针的QList< QThread* >
。private: QList<QThread*> freeThreads; // only free threads QList<QThread*> allThreads; // just to count the number of all threads
-
在插槽 freeThread(( 中使用 QObject 中的 sender(( 方法来获取信号发送者的指针,在本例中将是 QThread,它已经变得自由
void ThreadPool::freeThread() { // get the pointer to the thread that sent the signal: QObject* threadFreed = QObject::sender(); if( ! freeThreads.contains( threadFreed ) ) { // save the thread pointer in list freeThreads << threadFreed; } }
-
最后getFreeThread((可以看起来像这样:
QThread* getFreeThread() { if( ! freeThreads.isEmpty() ) { // take the first free thread return freeThreads.takeFirst(); } else { if(allThreads.size() < maxThreads ) { // create a new thread QThread* thread = new QThread(this); allThreads << thread; return thread; } else { // Maximum number of threads exceeded // and no free thread is available return NULL; } } }
此外,您还应该处理在addTask中返回NULL 指针的情况:
void ThreadPool::addTask(MyTask* task)
{
QThread *thread = getFreeThread();
if( ! thread )
{
// do something else
return;
}
// proceed with thread execution ...
}
相关文章:
- 如何监控QThread
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 等待 qthread 终止的正确方法是什么?
- 如何正确停止运行非循环QThread?
- Valgrind 在 QThread::start() 上报告内存泄漏
- 如何在 QThread 中传递引用
- 使用 QTimer、QThread 和进度条
- 为什么我不能调用 QMetaObject::invokeMethod(&threadObj, &QThread::start, Qt::QueuedConnection)?
- QThread::create 似乎没有将参数传递给函数
- QThread::create running on UI Thread
- std::condition_variable 在 QThread::run() 中的用法
- QThread moveToThread 不起作用
- QThread start() return value
- 在另一个 QThread 上运行成员方法时,无法将事件发送到其他线程拥有的对象
- 问题 (std::bad_alloc) 通过 QThread 中的 QSqlQuery 将大图像(约 36 MB)保存到
- 如何从 QWizardPage 和访问字段()运行 QThread
- 了解如何在不冻结事件循环的情况下在 QThread 中休眠/等待
- QMutex with QThread - prime number sekeer
- 如何使用 Win32 ThreadPool API?
- QThread threadpool