Creating and Terminating Threads

Hi All,

I am new to C++ and Threads.

I had a requirement where i needed to create a thread and if the execution of thread is not completed in 5 minutes i needed to terminate its execution and continue with other part of the code.

I used the below code to create the thread

1
2
3
_beginthread(FuncnCall,0,NULL);
						
HANDLE hThread = GetCurrentThread(); 


Then after this code, I used the below code to check for 5 minutes
1
2
3
4
5
6
7
8
9
10
11
12
for (int i=1;i<=0;i++)
{
        printf("Value of i=%d\n",i);
	if(threadFinished)
	{
		break;
	}
	else
	{
		Sleep(1000);
	}
}


After this if the value of "threadFinished" is false then i am terminating the thread like below
1
2
3
4
5
if(threadFinished == false)
{				
	TerminateThread(hThread,0);
	CloseHandle(hThread);
}


The Problem here is, after terminating the thread, the program abruptly closes by giving fatal error. Looks like memory leakage is happening after terminating the thread. Is it not the right way to safely exit the thread? Please help me in safely terminate the thread without any memory leaks and deadlocks!

Thank you.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686717%28v=vs.85%29.aspx
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:
* If the target thread owns a critical section, the critical section will not be released.
* If the target thread is allocating memory from the heap, the heap lock will not be released.
* If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
* If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.


Can't you instead have some shared variable that the thread can check from time to time to know it's time to terminate itself the a safe way, by simply returning from the thread function?
Thanks for your reply Peter.

Could you give me a small piece of code doing that if you dont mind? I am not that good in thread and c++.

Thanks again for your reply.
Topic archived. No new replies allowed.