Threads are created in the Windows API using the CreateThread() function, and just like in Pthreads, a set of properties such as security information, stack size, and thread flags are passed to the function. In the following program, we use the default values of these properties. (The default does not initially set the thread to a suspended state, but instead makes it eligible to be run by the CPU scheduler.) After the sum thread is created, the parent must wait for it to complete before it can output the value of Sum because the value is set by the summation thread. In the Pthread program, we use the pthread join() statement to make the parent thread wait for the summation thread. Here, using the WaitForSingleObject() function, we do the equivalent of this in the Windows API, which causes the creating thread to block until the summing thread has exited. In situations where you need to wait for multiple threads to complete, you can use the WaitForMultipleObjects() function. The function is passed four parameters -
For example, if THandles is an array of thread HANDLE objects of size N, the parent thread can wait for all of its child threads to complete this statement -
WaitForMultipleObjects(N, THandles, TRUE, INFINITE);
#include<windows.h> #include<stdio.h> DWORD Sum; /* data is shared by the thread(s) */ /* thread runs in this separate function */ DWORD WINAPI Summation(LPVOID Param){ DWORD Upper = *(DWORD*)Param; for (DWORD i = 0; i <= Upper; i++) Sum += i; return 0; } int main(int argc, char *argv[]){ DWORD ThreadId; HANDLE ThreadHandle; int Param; if (argc != 2){ fprintf(stderr,"An integer parameter is required</p><p>"); return -1; } Param = atoi(argv[1]); if (Param < 0){ fprintf(stderr,"An integer >= 0 is required</p><p>"); return -1; } /* create the thread */ ThreadHandle = CreateThread( NULL, /* default security attributes */ 0, /* default stack size */ Summation, /* thread function */ &Param, /* parameter to thread function */ 0, /* default creation flags */ &ThreadId); /* returns the thread identifier */ if (ThreadHandle != NULL){ /* now wait for the thread to finish */ WaitForSingleObject(ThreadHandle,INFINITE); /* close the thread handle */ CloseHandle(ThreadHandle); printf("sum = %d</p><p>",Sum); } }
The above is the detailed content of Windows Thread API in C Program. For more information, please follow other related articles on the PHP Chinese website!