Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QThread::getCurrentThread() from non-Qt thread

What will I get from QThread::getCurrentThread(), if it is called from non-Qt thread?

Thanks!

like image 916
andrii Avatar asked Apr 25 '13 05:04

andrii


People also ask

How do you run a function in QThread?

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.

How do you stop QThread in Qt?

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.

How do you wait for QThread to finish?

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.

What is QThread in Qt?

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().


1 Answers

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 pthreads.

#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.

like image 187
gatto Avatar answered Oct 20 '22 17:10

gatto