views:

361

answers:

2

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.

+3  A: 

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 !

Magnus Skog
Can't there be multiple UI threads?
Naveen
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.
Javier De Pedro
Left a comment in my post.
Magnus Skog
+6  A: 

Use the following code if you are using MFC application.

if(GetCurrentThreadId() == AfxGetApp()->m_nThreadID)
{
    //Main Thread
}
else
{
    //Not Main Thread
}
Shino C G