Criticalsection example

Criticalsection and CreateThread example (EnterCriticalSection LeaveCriticalSection)

#include <windows.h> 
#include <string> 
#include <iostream> 
#include <process.h>    /* _beginthread, _endthread */
long a=0;
long b=0;
int Threadcount=64;
int s=Threadcount;
CRITICAL_SECTION  gcs; 
void Submain(void *x)
{
	for (int L=0;L<1000;L++) 
		{

			a=a++;
			EnterCriticalSection(&gcs);
						b=b++;
			LeaveCriticalSection(&gcs);
		}

/*
    s=s-1;  //Simple synchronization technique. May be useful if you like to increase the thread count WaitForMultipleObjects support value defined for MAXIMUM_WAIT_OBJECTS 64
	if(s==0)
	{
		d=TRUE;
	}
*/
_endthread();
}

 
void main()

{

HANDLE *hThreads;
hThreads = new HANDLE[Threadcount] ;
InitializeCriticalSection(&gcs);
for (int i=0;i<Threadcount;i++)
{
hThreads[i]=	CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE  )Submain,  NULL,  0,  NULL);
 	
		if (hThreads[i]==NULL)
		{
			printf("\nThread creation failed for thread %d with error %d",i,GetLastError());
		}

}

DWORD rw=WaitForMultipleObjects(Threadcount,hThreads,true,INFINITE);
DeleteCriticalSection(&gcs);
//while(!d); //Simple synchronization technique 

printf("Value of a is:%d\n" ,a);
printf("Value of b is:%d\n" ,b);
system("pause");
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s