What will I get from QThread::getCurrentThread()
, if it is called from non-Qt thread
?
Thanks!
There are two main ways of running code in a separate thread using QThread: subclassing QThread and overriding run(); creating a “worker object” (some QObject subclass) and connecting it to QThread signals.
Calling QThread::quit() posts a termination message to this queue. When QThread::exec() will read it, it will stop further processing of events, exit infinite loop and gently terminate the thread.
Normally, with Qt you will have a QApplication based class with an event loop with signals and slots, that will not exit from the main function until you want to. In that case you can simply connect the QThread::finish() signal to a slot that checks if all threads are done.
Detailed Description. A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread. You can use worker objects by moving them to the thread using QObject::moveToThread().
QThread
is just a wrapper, behind the scene it uses native threads.
QThread::currentThread
creates and initialises a Q(Adopted)Thread
instance if it doesn't exist yet.
In case of unix it uses pthread
s.
#include <iostream>
#include <thread>
#include <pthread.h>
#include <QThread>
#include <QDebug>
void run() {
QThread *thread = QThread::currentThread();
qDebug() << thread;
std::cout << QThread::currentThreadId() << std::endl;
std::cout << std::this_thread::get_id() << std::endl;
std::cout << pthread_self() << std::endl;
thread->sleep(1);
std::cout << "finished\n";
}
int main() {
std::thread t1(run);
t1.join();
}
Output:
QThread(0x7fce51410fd0)
0x10edb6000
0x10edb6000
0x10edb6000
finished
I see that there is initialisation of Qt application main thread:
data->threadId = (Qt::HANDLE)pthread_self();
if (!QCoreApplicationPrivate::theMainThread)
QCoreApplicationPrivate::theMainThread = data->thread;
So there might be some side effects.
I'd advise not to mix QThread with non-Qt threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With