PostHeaderIcon Create Threads With WinAPI

This is also simple code, follows like below:

Thread Param:

// max thread counter
#define MAX_THREADS 5

// thread params(you can define yourself)
typedef struct _THREAD_PARAM
{
	DWORD i;
	DWORD dwRandom;
	DWORD dwData;
}THREAD_PARAM, *LPTREAD_PARAM;

Thread Process:

// thread process - print info about each thread
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
	LPTREAD_PARAM pData;
	pData=(LPTREAD_PARAM)lpParam;

	printf("TLD - %u, \t Parameters - %u, %u, %u\n",
		GetCurrentProcessId(),
		pData->i,pData->dwRandom,pData->dwData);

	//free heap
	HeapFree(GetProcessHeap(),0,pData);
	return 0;
}

Main Thread:

int main()
{
	LPTREAD_PARAM pData;
	DWORD dwTreadId[MAX_THREADS];
	HANDLE hThread[MAX_THREADS];

	printf("================ main begin ================\n");

         for (int i=0;i<MAX_THREADS;++i)
         {
             // alloc heap
             pData=(LPTREAD_PARAM)HeapAlloc(GetProcessHeap(),
                                            HEAP_ZERO_MEMORY,
                                            sizeof(THREAD_PARAM));
             if (pData==NULL)
             {
                 printf("HeapAlloc error;\n");
                 ExitProcess(2);
             }

             pData->i=i;
             pData->dwRandom=rand();
             pData->dwData=100;

             // create thread with param
             hThread[i]=CreateThread(
                            NULL,
                            0,
                            ThreadProc,
                            pData,
                            0,
                            &dwTreadId[i]);

             if (hThread[i]==NULL)
             {
                 ExitProcess(i);
             }
         }
	// main thread waits for all threads finished
	WaitForMultipleObjects(MAX_THREADS,
		hThread,
		TRUE,
		INFINITE);

	// close handle of each thread
	for (int i=0; i<MAX_THREADS; ++i)
    {
		CloseHandle(hThread[i]);
	}
	printf("================ main endl ================\n");
	return 0;
}
123,331 views

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Copyright © 2010 - C++ Technology. All Rights Reserved.

Powered by Jerry | Free Space Provided by connove.com