Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Iterate over qtcp servers to connect concurrently



  • I want to show data from several servers on the paint layer but didn't manage to do so.
    my code snippet is:
    window.cpp

        int index = -1;
        QMapIterator<QString,int> i(Servers::myMap);
        while (i.hasNext()) {
            i.next();
            index++;
            QThreadPool pool;
            QFuture<void> tr;
            client = new Client;
            client->ConnectToServer(i.key(),i.value());
            layer = new MPaintLayer(mapWidget);
            timer = new QTimer;
            tr = QtConcurrent::run(&pool,add_layer,mapWidget,client,timer,layer);
            timer->start(2000);
            qDebug() << index;
            qDebug() << i.key() << ": " << i.value()<< "\n\n\n";
            tr.waitForFinished();
    

    what's wrong in this approach?
    my add_layer function is:

    QObject::connect(timer,SIGNAL(timeout()),client,SLOT(online_slot()), Qt::QueuedConnection);
    mapWidget->addLayer(layer);
    mapWidget->update();
    

  • Lifetime Qt Champion

    @poormohammadf said in iterate over qtcp servers to connect:

    what's wrong in this approach?

    The better question - what do you try to achieve and why not simply do create a QTcpConnection, start a timer and connect to the next one when it times out? Why do you need threads at all here?



  • I use Marble widget to show stream data from multiple servers on the map. each connection should add their own layer on the map. therefore each connection should be separated thread.


  • Lifetime Qt Champion

    @poormohammadf said in iterate over qtcp servers to connect:

    therefore each connection should be separated thread.

    This is no reason to move the tcp stuff into an own thread since the QTcpSocket is async. It just doesn't make any sense. Your client is created in the main thread so all the work will be done in the main thread too. If you really want to use threads for whatsoever reason, I would suggest you to read the QThread documentation and examples to understand when something is running in a separate thread (and what you have to take care for) - currently this is just some stuff thrown together in the hope it works without understanding of the basics (and, as I said - completely unneeded for the needs).


Log in to reply