This code:
#include <QCoreApplication>
#include <QTcpServer>
#include <QHttpServer>
#include <QtConcurrent>
#include <QDebug>
QHttpServerResponse handleRequest(int id) {
qDebug() << "Start" << id << QThread::currentThread();
QThread::sleep(5);
qDebug() << "Finish" << id;
return QHttpServerResponse("response text\n");
}
int main(int argc, char **argv) {
QCoreApplication app(argc, argv);
QHttpServer server;
server.route("/", [] (int id) {
return QtConcurrent::run(&handleRequest, id);
});
auto tcpserver = new QTcpServer(qApp);
if (!tcpserver->listen(QHostAddress::Any, 30000) || !server.bind(tcpserver)) {
return -1;
}
qDebug() << "Listening on port" << tcpserver->serverPort();
return app.exec();
}
Produces results like this:
./test
Listening on port 30000
Start 0 QThreadPoolThread(0x5d512f61d580, name = "Thread (pooled)")
Start 2 QThreadPoolThread(0x5d512f8b6400, name = "Thread (pooled)")
Start 1 QThreadPoolThread(0x5d512f62ecb0, name = "Thread (pooled)")
Start 4 QThreadPoolThread(0x5d512f630430, name = "Thread (pooled)")
Start 3 QThreadPoolThread(0x5d512f8b6ce0, name = "Thread (pooled)")
Finish 0
Finish 4
Finish 1
Finish 2
Finish 3
^C
when tested with:
curl -o - http://localhost:30000/0 &
curl -o - http://localhost:30000/1 &
curl -o - http://localhost:30000/2 &
curl -o - http://localhost:30000/3 &
curl -o - http://localhost:30000/4 &
Request processing is interleaved, multi-threaded. The size of the thread pool is limited so more requests will start waiting. Using curl --parallel changes the behaviour with respect to the first request curl sends.