Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if code is running on the ui thread or a working thread (MFC Visual C++)

I have a function that is being called from different threads in the application. I need to know whether the thread that executes the code is the main thread(ui thread) or a working thread.

Any suggestion?

Thanks.

like image 684
Javier De Pedro Avatar asked May 27 '09 08:05

Javier De Pedro


2 Answers

Use the following code if you are using MFC application.

if(GetCurrentThreadId() == AfxGetApp()->m_nThreadID)
{
    //Main Thread
}
else
{
    //Not Main Thread
}
like image 136
Shino C G Avatar answered Oct 26 '22 10:10

Shino C G


Use GetCurrentThread() or GetCurrentTreadId() and compare it with the known HANDLE or id of the main thread.

Can't there be multiple UI threads?

Sure there can, but only one main ui thread.

Ok. But, is there a way to know the HANDLE or ID of the main thread from this code? I mean something like GetMainThread or GetMainThreadID. I would like not to modify other parts of the application (if possible). BTW, Thanks for your answer.

Sorry, I was out to lunch and you already got your answer. But might as well reply anyway. GetCurrentThreadId() can of course be used during execution of your main ui thread and be cached for later comparision. Somewhere during execution of your application, there will be only one thread, e.g. in WinMain() before any other thread has been created.

Cheers !

like image 44
ralphtheninja Avatar answered Oct 26 '22 12:10

ralphtheninja