5

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.

Javier De Pedro
  • 2,219
  • 4
  • 32
  • 49
  • Possible duplicate of [How to get the main thread ID of a process (known by its ID)?](http://stackoverflow.com/questions/15597066/how-to-get-the-main-thread-id-of-a-process-known-by-its-id) – TarmoPikaro Aug 25 '16 at 09:37

3 Answers3

15

Use the following code if you are using MFC application.

if(GetCurrentThreadId() == AfxGetApp()->m_nThreadID)
{
    //Main Thread
}
else
{
    //Not Main Thread
}
Shino C G
  • 1,237
  • 11
  • 17
  • I found a strange thing - the WinAPI function [IsGUIThread()](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-isguithread) which is intended to do exactly the same thing, fails to detect non-GUI threads. Your solution works, but IsGUIThread(FALSE) always returns TRUE for all my background threads. – Mar Aug 06 '20 at 09:00
5

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 !

rtn
  • 127,556
  • 20
  • 111
  • 121
  • 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 May 27 '09 at 08:52
  • Note that MSDN says about GetCurrentThread: "The function cannot be used by one thread to create a handle that can be used by other threads to refer to the first thread. The handle is always interpreted as referring to the thread that is using it. A thread can create a "real" handle to itself that can be used by other threads, or inherited by other processes, by specifying the pseudo handle as the source handle in a call to the DuplicateHandle function." ... as I understand it, you also need to call DuplicateHandle when trying to use a handle returned by GetCurrentThread on multiple threads. – Andreas Oct 24 '20 at 12:06
1

AfxGetApp()->GetMainWnd()

will return the same thing that AfxGetMainWnd() would return if called from the main thread.

diox8tony
  • 348
  • 3
  • 13