views:

180

answers:

4

I need to be able to suspend and resume the main thread in a Windows C++ app. I have used

handle = GetCurrentThread();
SuspendThread(handle);

and then where is should be resumed

ResumeThread(handle);

while suspending it works, resuming it does not. I have other threads that are suspended and resumed with no problems, is there something that is different with the main thread.

I have done a lot of threading working in C# and Java but this is the first time I have done any in C++ and I'm finding it to be quite a bit different.

+2  A: 

The easiest way to get the same result is to CreateEvent and have main thread WaitForSingleObject on it, then wake it up with SetEvent from another thread.

Nikolai N Fetissov
Just keep in mind that so long as the main thread is suspended or wait-ed, the message pump will not be pumping. Among other thing, the most obvious result of this is that the GUI will be non-responsive.
John Dibling
Wouldn't suspending the main thread have the same result?
Nikolai N Fetissov
Is that not what I said? :)
John Dibling
Oh, I see. Need better reading glasses :)
Nikolai N Fetissov
+5  A: 

GetCurrentThread returns a "pseudo handle" that can only be used from the calling thread. Use DuplicateHandle to create a real handle that another thread can use to resume the main thread.

See http://msdn.microsoft.com/en-us/library/ms683182%28VS.85%29.aspx

Mike Seymour
God, I love Microsoft :)
Nikolai N Fetissov
+6  A: 

Are you using the "handle" value you got from GetCurrentThread() in the other thread? If so that is a psuedo value. To get a real thread handle either use DuplicateHandle or try

HANDLE hThread = OpenThread(THREAD_ALL_ACCESS, FALSE, GetCurrentThreadId());

tyranid
Thanks, this worked.
Android
+1  A: 

And, here's an example that shows what some of the folks have suggested before.

#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <process.h>

HANDLE g_hMainThread;
void TheThread(void *);

int _tmain(int argc, _TCHAR* argv[])
{
    g_hMainThread = OpenThread(THREAD_ALL_ACCESS,
                               FALSE,
                               GetCurrentThreadId());
    printf( "Suspending main thread.\n" );
    _beginthread(TheThread, 0, NULL);
    SuspendThread(g_hMainThread);
    printf( "Main thread back in action.\n" );
    return 0;
}

void TheThread(void *)
{
    DWORD dwStatus = ResumeThread(g_hMainThread);
    DWORD dwErr = GetLastError();
    printf("Resumed main thread - Status = 0x%X, GLE = 0x%X.\n",
           dwStatus,
           dwErr );
}
Ranju V