Home > OS >  How to get winapi thread HANDLE from QThread?
How to get winapi thread HANDLE from QThread?

Time:12-14

I would like to use CancelSynchronousIo() function, so I need a thread handle. In my QT app I have two threads: mainThread ( gui ) and secondThread for calculations. I would like to use CancelSynchronousIo() in mainThread to cancel operations in the secondThread. I don't know how to get winapi thread handle from Qt class.

I tried:

MainThread:

   thread = new QThread(this);
   simpleObject = new SimpleClass();
   connect(this, &MainWindow::getHandle, simpleObject , &simpleClass::getHandle);
   simpleObject->moveToThread(thread);
   thread->start();

SimpleObject, which is in the second thread:

void simpleClass::getHandle()   // this is slot in simpleObject, which is in the second thread
{
   emit handleFromSecondThread(GetCurrentThread());
}

I see that value from GetCurrentThread() in second thread is the same as value from GetCurrentThread() in mainThread

CodePudding user response:

You need QThread::currentThreadId(), which returns the ID of the thread it is executed in, i.e. it calls GetCurrentThreadId(). You can then get the handle by calling OpenThread() with that ID.

Note that this is different from GetCurrentThread() which returns a constant that simply means "the current thread".

CodePudding user response:

AFAIK, QThread does not provide access to either the HANDLE or the ID of the underlying OS thread. The only way I can think of for you to get the thread's HANDLE is to derive a new class from QThread and override its virtual run() method to do one of the following:

  • call QThread::currentThreadId() (or GetCurrentThreadId() directly), and then pass the returned ID to OpenThread().

  • call GetCurrentThread(), and then pass the returned pseudo-handle to DuplicateHandle().

  • Related