【问题标题】:QThread threadpoolQThread 线程池
【发布时间】:2017-03-31 23:20:47
【问题描述】:

我正在尝试使用 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 的向量中的每个线程是否是免费的。

【问题讨论】:

  • 为了完整起见,您可以使用一个 QThreadPool 类。

标签: c++ qt threadpool


【解决方案1】:
  1. 您实际上并不需要 QVector&lt;QPair&lt;bool, QThread&gt;&gt; 来跟踪池中的所有线程,而是使用仅包含指向空闲线程的指针的 QList&lt; QThread* &gt;

    private:
         QList<QThread*> freeThreads; // only free threads
         QList<QThread*> allThreads; // just to count the number of all threads
    
  2. 在槽 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;
         }
    }
    
  3. 最后 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 ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 2013-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 2010-09-18
    相关资源
    最近更新 更多