Can I create QTcpServer in another thread?
Solved
General and Desktop
-
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? -
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)
-
Going from the user in this thread
https://forum.qt.io/topic/59687/qthread-or-std-threadI would say using Signal&Slots from an std::thread is near impossible 🤷♂️
-
Good to know, thanks.