Multithreading is a vast subject. This article aims to cover only some basics on
multithreading. It also gives a small sample code to write a Multi threaded program in Win32.
Multithreading is nothing but executing operations
parallel. A multi-threaded operation will usually
be embedded inside a function which returns a DWORD and takes a void * as a parameter. A program can have
any number of simultaneous threads.
A thread can have priorities. It ranges from Low to High priority. Most of the normal applications can
sufficiently operate with NORMAL priority threads. Well let's start writing some real code now.
#include <Windows.h>
#include <iostream.h>
#include <string.h>
DWORD WINAPI StartThread(LPVOID iValue)
{
char lszParam[3];
strcpy(lszParam,(char *)iValue);
int iStart = atoi(lszParam);
for(int i=iStart;i<=iStart+10;i++)
cout<<i<<endl;
return 0;
}
void main()
{
HANDLE hThread1,hThread2;
DWORD dwGenericThread;
char lszThreadParam[3];
strcpy(lszThreadParam,"3");
hThread1 =
CreateThread(NULL,0,StartThread,&lszThreadParam,0,&dwGenericThread);
if(hThread1 == NULL)
{
DWORD dwError = GetLastError();
cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
return;
}
WaitForSingleObject(hThread1,INFINITE);
//Second thread creation
strcpy(lszThreadParam,"30");
hThread2 =
CreateThread(NULL,0,StartThread,&lszThreadParam,0,&dwGenericThread);
if(hThread1 == NULL)
{
DWORD dwError = GetLastError();
cout<<"SCM:Error in Creating thread"<<dwError<<endl ;
return;
}
WaitForSingleObject(hThread2,INFINITE);
}
A Win32 thread function has to be declared with an input
parameter as void * type and return type as DWORD.
As the input parameter is of type void *, we can pass any
amount of data into this thread.
A
typical format through which the parameters will be passed is
by using a structure or a class. This struct or class will be
loaded with all data members which are needed by the thread
and then its reference is passed inside. The above example has a thread which takes a parameter as a void * and converts it to a number.
This is just a simple example.
CreateThread supplies the value of "lszThreadParam" as the thread parameter.
It returns a thread handle of type HANDLE. This handle
can be used for further operations like waiting for the thread
to finish, terminating the thread etc., This HANDLE, DWORD
etc., data types and lots of other types are invented by
Charles semonyi, while he was working with the development of
WIN32 SDK. This type of naming convention is called as Hungarian
notation.
WaitForSingleObject is another windows function which Waits till the thread returns. This function is used in
many Win32 applications as an Inter Process messaging mechanism. This is also
used for waiting on Event Objects which are created using
CreateEvent function.
Note: This article will get updated with more examples and notes.