In Win32 I want to suspend a thread using Suspend(GetCurrentThread()); but I find I cannot resume it using ResumeThread(suspend thread handle); But I find nothing happened.
Here it’s my code.
HANDLE C;
DWORD WINAPI A (LPVOID in)
{
C = GetCurrentThread();
cout << "1";
SuspendThread (C);
cout << "4";
return 0;
}
DWORD WINAPI B (LPVOID in)
{
Sleep (200);
cout << "2";
ResumeThread (C);
cout << "3";
return 0;
}
int main()
{
CreateThread (NULL, 0, A, NULL, 0, NULL);
CreateThread (NULL, 0, B, NULL, 0, NULL);
Sleep (INFINITE);
return 0;
}
And all I get on screen is 123.
It is possible right now that when
BcallsResumeThread, the variableCcontains an uninitialized value.However, the current reason why your code does not work is that
GetCurrentThreadonly returns a pseudo-thread handle, a value interpreted to mean the current thread handle. To get the real one which can be used from other threads, you can take the one from the return of the firstCreateThreadcall or convert the pseudo-handle withDuplicateHandle.Edit: Using method 1:
In fact there is another problem with your code which is that handles returned from
CreateThreadare being ignored when they should be closed. Also there is a lack of error checking but I have assumed you’ve omitted that for brevity.You should also note that, depending on the timing of the context switch it is actually possible for the above code to output:
Using method 2: