Canceling a Thread Program Example
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <Windows.h>
#include <stdio.h>
DWORD WINAPI thread_function(LPVOID arg)
{
wprintf(Lthread_function() is running. Argument received was \%s\\n, arg);
for(int i = 0; i < 10; i++)
{
wprintf(LThread is running pass #%d, ID %u...\n, i, GetCurrentThreadId());
// Give enough time...
Sleep(1000);
}
return 100;
}
void wmain()
{
HANDLE a_thread;
DWORD thread_result, dwThreadId;
WCHAR message[] = LHello World;
wprintf(LCurrent process ID is %u\n, GetCurrentProcessId());
wprintf(LCurrent thread (main()) ID is %u\n, GetCurrentThreadId());
wprintf(L\n);
// Create a new thread.
a_thread = CreateThread(NULL, 0, thread_function, (LPVOID)message, 0, &dwThreadId);
if (a_thread == NULL)
{
wprintf(LCreateThread() failed, error %u, GetLastError());
exit(EXIT_FAILURE);
}
else
wprintf(LCreateThread() is OK! Thread ID is %u\n, dwThreadId);
// Give enough time, else deadlock
Sleep(3000);
// If the function succeeds, the return value is nonzero.
// If the function fails, the return value is zero.
if (!TerminateThread(a_thread, 0))
{
wprintf(LTerminateThread() - Thread cancellation failed! error %u\n, GetLastError());
exit(EXIT_FAILURE);
}
else
wprintf(LTerminateThread() - Cancelling thread %u\n, dwThreadId);
wprintf(L\n);
wprintf(LWaiting for thread %u to finish...\n, dwThreadId);
if(WaitForSingleObject(a_thread, INFINITE) != WAIT_OBJECT_0)
{
wprintf(LWaitForSingleObject(), failed, error %u\n, GetLastError());
exit(EXIT_FAILURE);
}
else
wprintf(LWaitForSingleObject()is OK! Some event should be signaled!\n);
wprintf(L\n);
// If the function succeeds, the return value is nonzero.
// If the function fails, the return value is zero.
if(GetExitCodeThread(a_thread, &thread_result) != 0)
wprintf(LGetExitCodeThread() is OK!, Exit code %u\n, thread_result);
else
wprintf(LGetExitCodeThread() failed, error %u\n, GetLastError());
if(CloseHandle(a_thread) != 0)
wprintf(La_thread handle was closed successfully!\n);
else
wprintf(LFailed to close a_thread handle, error %u\n, GetLastError());
exit(EXIT_SUCCESS);
}
Build and run the project. The following screenshot is a sample output.
The execution may be hanging. Can you find the reason?
When verifying the condition using Windows Task Manager, we can see a single thread is still running.