Search within this blog

Thursday, June 17, 2010

Creating Threads in Windows

Like process you can also create threads in windows at ease. The thing is similar to pthread_create in Linux. This code is mostly taken from Galvin. You use the CreateThread API call and pass the thread function to it. The following code illustrates this. The code is taken from Silberschatz, Galvin, Gagne: Operating System Concepts, 7th Edition: Figure 4.7. But the code was not working for some reason, so, i made a few changes and post it here. The changes are in bold. I also added a few comments to describe the code more elaborately.

File: Win32ThrdCreat.c
---------------------------------------

/*
MULTITHREADED C PROGRAM USING WIN32 API

CREATES A CHILD THREAD TO CARRY OUT 'thread_func' FUNC.

MAIN THREAD AND CHILD THREAD RUNS CONCUURENTLY

1/2 S DELAY IS IMPOSED IN EACH THREAD FOR DEMONSTRATION PURPOSE

Galvin p 31
Modified by: Joydip Datta
Date: 9:56 AM Thursday, December 14, 2006
*/

#include
#include

DWORD Sum=0; //shared data

//the thread runs in this separate function
DWORD WINAPI thread_function(LPVOID Param)
{
DWORD Upper = * (DWORD*) Param;
long i;

for(i= 0; i<= Upper; i++){
printf("Child Thread: %ld\n",i);
Sum+=i;
Sleep(500);//pause for 1/2 s
}

return 0;
}

int main(int argc, char * argv[])
{
DWORD ThreadId;
HANDLE ThreadHandle;
long Param,i;

//perform basic err chk
if(argc != 2){
fprintf(stderr, "An Integer parameter is requirred");
return -1;
}

Param = atoi(argv[1]);

if(Param <>
fprintf(stderr,"An Integer param >=0 is requirred");
return -1;
}

//create the thread
ThreadHandle = CreateThread(
NULL, //default security attribs
0, //default stack size
thread_function, //pointer to thread func
&Param, //parameter to Thread func
0, //default cration flags
&ThreadId//returns the thread Id
);


for(i=0;i
printf("Main Thread: %ld\n",i);
Sleep(500); //pause for 1/2 s
}

if (ThreadHandle != 0) {
//wait for the thread object to finish
WaitForSingleObject(ThreadHandle, INFINITE);

//close the thread handle
CloseHandle(ThreadHandle);

printf("Sum: %ld",Sum);
}
return 0;
}

2 comments:

lost_in_woods said...

amazing picture and blog visit us for disscount andaman holiday packages

John Bradon said...

THANKS FOR SHARING THE CONTENT
Beach hotels in Portblair
Beach hotels in Havelock