Hi all , I am having problem about killing multiple treads in my program at the same time, here is my code:

int main()
{
while(1)
{
i++;
HANDLE thread =(HANDLE)_beginthread(TheThread, 0, NULL);
if(i==10)
break;
}

Sleep(3000);

TerminateThread(thread,0);

return 0;
}

now "TerminateThread(thread,0);" will only terminate the 10th thread , but how i will be able to terminate the 10 threads at once, also i don't want to create a new variable for new threads and terminate them like:

HANDLE a,b,c;
a =(HANDLE)_beginthread(TheThread, 0, NULL);
b =(HANDLE)_beginthread(TheThread2, 0, NULL);
c =(HANDLE)_beginthread(TheThread3, 0, NULL);

Sleep(3000);

TerminateThread(a,0);
TerminateThread(b,0);
TerminateThread(c,0);

as it will be hard to write the program if i want to create 300 threads at once, so please help me :(


Thanks in advance

create an array of HANDLE objects so that you can put the code in a loop.

const int MaxThreads = 20;
HANDLE hThreads[MaxThreads];

for(int i = 0; i < MaxThreads; i++)
   hThreads[i] = (HANDLE)_beginthread(TheThread, 0, NULL);

...

for(int i = 0; i < MaxThreads; i++)
   TerminateThread(hThreads[i],0);

create an array of HANDLE objects so that you can put the code in a loop.

const int MaxThreads = 20;
HANDLE hThreads[MaxThreads];

for(int i = 0; i < MaxThreads; i++)
   hThreads[i] = (HANDLE)_beginthread(TheThread, 0, NULL);

...

for(int i = 0; i < MaxThreads; i++)
   TerminateThread(hThreads[i],0);

THANKS!!!!! :twisted:

I have slightly modify the terminate thread program and used it in my proxy checking program, but its crashing after creating and terminating 1st set of threads , I cant figure out whats the problem :( , here is my code:

char zz[4000];

int main()
{
int i=0;
const int MaxThreads = 40;
HANDLE hThreads[MaxThreads];
string line;

   ifstream infile("proxy.txt");
   while ( getline(infile, line) )
   {
	   i++;

	   strcpy(zz,line.c_str());

	   hThreads[i] =(HANDLE)_beginthread(TheThread, 0, NULL);
	   cout<<hThreads[i]<<endl;

	   if (i==MaxThreads)
	   {
		   cout<<i<<endl;
		   i=0;
		   Sleep(15000);
		 
		   for(int x = 0; x <=MaxThreads; x++)
   TerminateThread(hThreads[x],0);


	   }
	   
	   	 
	   
	   cout<<zz<<endl;
Sleep(10);

   }

    Sleep(15000);
   		   for(int x = 0; x <=MaxThreads; x++)
   TerminateThread(hThreads[x],0);
   MessageBoxA(NULL,"complete","complete",NULL);
   return 0;
}

please help me to figure out the problem :)

Thanks in advance

line 13: you are incrementing i too soon which is causing theThreads[0] to be an uninitialized variable. Move that line down to line 19.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.