Click here to Skip to main content
15,899,937 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all,
the simple program below will create two threads using CreateThread API and then simply returns from the thread depending on the simple flag but two thread created will not be ended if i view the handles in process explorer
<br />
<br />
bool killthread1 = false,killthread2=false;<br />
void thread1()<br />
{<br />
        while(1)<br />
	{<br />
		if (killthread1)<br />
		{<br />
			printf("thread1 killed\n");<br />
			return;<br />
		}<br />
	}<br />
}<br />
<br />
void thread2()<br />
{<br />
	while(1)<br />
	{<br />
		if (killthread2)<br />
		{<br />
			printf("thread2 killed\n");<br />
			return;<br />
		}<br />
	}<br />
}<br />
<br />
int _tmain(int argc, _TCHAR* argv[])<br />
{<br />
	HANDLE th1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(thread1),NULL,0,0);<br />
	HANDLE th2 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(thread2),NULL,0,0);<br />
	getch();<br />
	killthread1=killthread2=true;<br />
	getch();<br />
	return 0;<br />
}<br />


In debug mode visual studio shows that 2 threads are ended before executing return 0, but "process explorer" shows they are alive, what is wrong in this??
Posted

wrote:
bool killthread1 = false,killthread2=false;


wrote:
but two thread created will not be ended if i view the handles in process explorer


This is because the flags that you're using to check for the thread termination condition is NOT declared as volatile.

Therefore, the optimiser must have completely removed the check!

Please read this: http://www.flounder.com/workerthreads.htm[^]
 
Share this answer
 
v4
NO assigning both BOOL as volatile also the scenario is not changing, VS shows both are dead, but the "process explorer" shows both as alive
 
Share this answer
 
Process Explorer shows that the kernel thread objects are alive - you should call CloseHandle() for th1 and th2.
 
Share this answer
 
As stated in the earlier answer, if you don't use CloseHandle on the thread handles, you will have a handle leak as reported by Process Explorer. The actual thread of execution has ended and the memory allocated for the thread like the stack, TLS etc. have been deallocated. But the handle still remains valid in the handle table untill you explicitly close it using CloseHandle.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900