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

Can I create QTcpServer in another thread?



  • I want to create qtcpserver in a separate netns. So I create it like this.

    QTcpServer *x11Server = nullptr;
    std::thread thread1([&]{
            if(setns(open("/var/run/UE", O_RDONLY), CLONE_NEWNET)){
                perror("setns");
                exit(-1);
            }
            x11Server = new QTcpServer;
            x11Server->listen(QHostAddress::Any, 6010);
        });
    connect(x11Server, &QTcpServer::newConnection, [=]{
    //todo
    });
    

    I put it in another thread to avoid setns influencing current main thread.
    In later code I will connect x11Server's sinal with something. Is this safe?


  • Moderators

    You definitely can create QTcpServer in another thread, it is safe and supported scenario. I am not sure if using std::thread for this purpose is good:

    • will it spin a new QEventLoop for that thread? I doubt it
    • connect() likely won't know that QueuedConnection has to be used - you need to remember to set it manually for all inter-thread connections (it's a good practice anyway)

  • Moderators

    Going from the user in this thread
    https://forum.qt.io/topic/59687/qthread-or-std-thread

    I would say using Signal&Slots from an std::thread is near impossible 🤷‍♂️


  • Moderators

    Good to know, thanks.


Log in to reply