I have a simple program that creates a thread, loops twenty times and then makes a call to close itself and perform the necessary cleanup.
When I debug the program it reaches the ExitThread(); method and pauses, ignoring the printf(); I have set up after it to signal to me it's closed.
Is this normal or am I forgetting to do something? I'm new to threading using C.
Main()
void main()
{
Time t;
int i = 0;
StartTimer();
for(i = 0; i < 20; i++)
{
t = GetTime();
printf("%d.%.3d\n", t.seconds, t.milliseconds);
Sleep(100);
}
StopTimer();
}
Thread Creation
void StartTimer()
{
DWORD threadId;
seconds = 0;
milliseconds = 0;
// Create child thread
hThread = CreateThread(
NULL, // lpThreadAttributes (default)
0, // dwStackSize (default)
ThreadFunc, // lpStartAddress
NULL, // lpParameter
0, // dwCreationFlags
&threadId // lpThreadId (returned by function)
);
// Check child thread was created successfully
if(hThread == NULL)
{
printf("Error creating thread\n");
}
}
Thread Close
void StopTimer()
{
DWORD exitCode;
if(GetExitCodeThread(hThread,&exitCode) != 0)
{
ExitThread(exitCode);
printf("Thread closed");
if(CloseHandle(hThread))
{
printf("Handle closed");
}
}
}
Edit:
I've realised that ExitThread() stops the executing thread, therefore I have attempted to use a different method to stop the timer but i'm still left with the same result.
void StopTimer()
{
WaitForSingleObject(hThread,INFINITE);
}
Solution:
The reason the program was stopping at the WaitForSingleObject() call and not progressing no matter how long it took was because the operation it was waiting on had an infinite loop.
It would be waiting for an infinite loop to finish, not the best thing to do. Changing the delay of WaitForSingleObject() to something more reasonable, such as 100 allowed the program to run normally.
Thanks for all the input.