QThreadPool问题:未能完成所有任务?

时间:2015-04-21 16:36:02

标签: c++ multithreading qt

我有以下代码:

/////////////////////////////////
//main.cpp
#include <QCoreApplication>
#include "myserver.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MyServer server;
    server.startServer();

    return a.exec();
}
/////////////////////////////////////////////////
//myserver.cpp
#include "myserver.h"
#include "myrunnable.h"

MyServer::MyServer(QObject *parent)
{
    pool = new QThreadPool(this);
    pool->setMaxThreadCount(10);
}

void MyServer::startServer()
{
    for (int i = 0; i < 11; i++)
    {
        MyRunnable *task = new MyRunnable();
        task->setAutoDelete(true);
        pool->start(task);
    }
}
/////////////////////////////////////////////////
//myrunnable.cpp
#include "myrunnable.h"
#include <qdebug.h>
MyRunnable::MyRunnable()
{
}

void MyRunnable::run()
{
    qDebug() << "Run";
}
/////////////////////////////////
// MyServer.h

#ifndef MYSERVER_H
#define MYSERVER_H

#include <QTcpServer>
#include <QThreadPool>
#include <QDebug>

class MyServer : public QObject
{
    Q_OBJECT
public:
    explicit MyServer(QObject *parent = 0);
    void startServer();

protected:

signals:

public slots:

private:
    QThreadPool *pool;
};

#endif // MYSERVER_H
/////////////////////////////////
// myrunnable.h

#ifndef MYRUNNABLE_H
#define MYRUNNABLE_H

#include <QRunnable>
#include <QTcpSocket>
#include <QDebug>


class MyRunnable : public QRunnable
{
public:
    MyRunnable();

protected:
    void run();

public:
    qintptr socketDescriptor;

};

#endif // MYRUNNABLE_H

///////////////////////////
//project file
QT       += core
QT       += network
QT       -= gui

TARGET = QTcpServerThreadPool
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app


SOURCES += main.cpp \
    myserver.cpp \
    myrunnable.cpp

HEADERS += \
    myserver.h \
    myrunnable.h

我运行我的代码希望通过调用startServer函数,它将给我11在屏幕上运行打印。但它从未这样做过。它在屏幕上打印出一些Run但从未打印过。

由于stackoverflow,程序有时会崩溃。我检查了调用堆栈,它是由一些奇怪的QMutex递归引起的。

所以我认为由于QThreadPool和QRunnable的使用,我的代码必须存在一些严重的线程相关问题。 但是,在阅读了Qt的文档后,我无法弄清楚它是什么......

1 个答案:

答案 0 :(得分:0)

您的问题可能被误诊,问题很可能出在QDebug而不是QThreadPool

替换以下代码

void MyRunnable::run()
{
    QTextStream cout(stdout, QIODevice::WriteOnly);
    cout << "Run" << endl;
}