PDA

View Full Version : Multithreading QThreads that keep a TCP connection and are reused



yonobi
30th April 2015, 22:07
I'm really unsure of how to address this problem so i will explain it first. I need to run a number of threads that each connect to some application via TCPSocket, so far no problem. The application is quite time consuming that is why i want it to run parallel on multiple threads and one thread each to communicate with it. Once the computation is finished i want to send the results to another thread collecting the results. Therefor i wrote a Worker class:


class Worker : public QObject {
Q_OBJECT

public:
Worker();
Worker(int port);
~Worker();
QTcpSocket* sock;
void insert();

public slots:
void connect();
void process(const int &id, const QString &param, const int &arity);

signals:
void ready();
void finished(const int &id, const int &consistent, const QString &result);
void error(QString err);
};
Now that superThread is supposed to work off a huge file and needs to spread it around the threads, and then receive and handle the results. My approach so far is another superThread that is connected in the main() as follows:


QThread* superThread = new QThread();
supWorker* super = new supWorker();
for (int i = 0; i < nrWorkers; i++){
Worker* worker = new Worker(portRange+i);
QThread* workerThread = new QThread();
QThread::connect(workerThread, SIGNAL(started()), worker, SLOT(connect()));
worker->moveToThread(workerThread);
workerThread->start();
QThread::connect(super, SIGNAL(process(int, QString, int)), worker, SLOT(process(int,QString,int)));
QThread::connect(worker, SIGNAL(finished(int, int, QString)), super, SLOT(handleResult(int, int, QString)));
}
The problem this way is obviously that i can only send the SIGNAL to all connected threads. What i want the superThread to do is send arguments to only one of the threads. I don't know how i can handle the connection so that only one of the working threads receives it?

Any help or architectural ideas much appreciated, thanks in advance.

jefftee
1st May 2015, 03:17
If you want to split up a large file and processes pieces of it in separate threads and then synchronize the results, then QtConcurrent map/reduce may be much easier to implement. Have you looked at that rather than creating/managing your own threads?

yonobi
1st May 2015, 12:17
roughly yes, but i could not find an appropiate example that fits my needs. :(