I'm using threaded application written in Qt (C++).
I need to make get/post request very often from separate threads.
Qt doc says:
One QNetworkAccessManager instance should be enough for the whole Qt application. Since QNetworkAccessManager is based on QObject, it can only be used from the thread it belongs to.
Is static thread_local QNetworkAccessManager
good choice for my purpose?
No, not a good choice.
You shouldn't create static or global QObject
subclass instances, because you generally need them to be created after the Qt application object has been created (a lot of Qt stuff depends on the application object existing already). C++ does not really provide very good control over when static objects are actually created, and here you want to have that control.
Just use a pointer and new
to create the QNetworkAccessManager
instance, as many of them as you want. You could create them in the right thread directly, or you could create them in some other (usually main) thread and move them to the right thread.
To get them destroyed properly, when they don't have a natural parent (because the parent must live in the same thread!), connect the their thread's QThread::finished
signal to the objects QObject::deleteLater
slot, and they will get cleanly deleted when the thread finishes.
If you want a plain function, which uses the current thread's QNAM instance, you could have thread-local static pointer. Something like
static thread_local *thread_qnam;
void myfunc() {
if (!thread_qnam) {
thread_qnam = new QNetworkAccessManager;
connect(QThread::currentThread, &QThread::finished(), thread_qnam, &QObject::deleteLater);
// Whatever other setup you need.
// It'd probably be good idea to wrap this in a function.
}
// Use thread_qnam...
}