Win32 Threads

The Win32 threads are implemented in the kernel space of Windows OS. The multi-threaded applications can use the Win32 API library similar to Pthread library.

Advertisements

We must include Windows.h header file while using win32 API. In the example program below, similar to Pthread – Sum is shared between threads and is the global variable of type DWORD (32-bit integer).

Advertisements

The function Summation () is the second thread created by main thread.

#include <windows.h>
#include <stdio.h>
DWORD Sum; /* data is shared by the threads */
/* the 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;
/* perform some basic error checking */

if (argc != 2 ) {
fprintf(stderr,"An integer parameter is required\n");
return -1;
}
Param = atoi(argv[1]);
if (Param < 0) {
fprintf(stderr,"An integer >= 0 is required\n");
return -1;
}
//create the thread 
ThreadHandle = CreateThead(
NULL, //default security attributes
0, // default stack size
Summation, //thread function
&Param, //parameter to thread function
0, //default creation flag
&ThreadId); //returns the thread identifier

if (ThreadHandle != NULL){

// wait for thread to finish
WaitForSingleObject(ThreadHandle, INFINITE);

//close the thread handle
CloseHandle(ThreadHandle);

printf("sum = %d\n", Sum);
}
}

The CreateThread() function create the thread when attributes are passed as parameters. The attributes are stack size, a flag to ensure blocking state during thread start, function Summation and its parameters.
The WaitForSingleObject() make parent thread to go to blocking state and wait until Summation () thread is completed.

References

  • Abraham Silberschatz, Peter B. Galvin, Greg Gagne (July 29, 2008) Operating System Concepts, 8 edn., : Wiley.
  • Tanenbaum, Andrew S. (March 3, 2001) Modern Operating Systems, 2nd edn., : Prentice Hall.

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.