Wednesday 11 March 2009

Multi-threading with Thread Synchronisation

Here is an example explaining the concept of multiple threads and their synchronisation:


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Example from http://www.adrianxw.dk/SoftwareSite/Threads/Threads2.html
//This shows an example of Multithreading and thread synchronisation
#include <windows.h>
#include <process.h>
#include <iostream>
using namespace std;

void
Func1(void *);
void
Func2(void *);

CRITICAL_SECTION Section; //This will act as Mutex


int
main()
{

HANDLE hThreads[2];
InitializeCriticalSection(&Section);

//Create two threads and start them
hThreads[0] = (HANDLE)_beginthread(Func1, 0, NULL);
hThreads[1] = (HANDLE)_beginthread(Func2, 0, NULL);

//Makes sure that both the threads have finished before going further
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);

//This is done after all threads have finished processing
DeleteCriticalSection(&Section);

cout << "Main exit" << endl;
return
0;
}


void
Func1(void *P)
{

int
Count;

for
(Count = 1; Count < 11; Count++)
{

EnterCriticalSection(&Section);
cout << "Func1 loop " << Count << endl;
LeaveCriticalSection(&Section);
}

return
;
}


void
Func2(void *P)
{

int
Count;

for
(Count = 10; Count > 0; Count--)
{

EnterCriticalSection(&Section);
cout << "Func2 loop " << Count << endl;
LeaveCriticalSection(&Section);
}

return
;
}





The output is as follows:
Complete explanation of the above program is available here.

2 comments:

  1. Nice simple example, thank you.

    ReplyDelete
  2. thaks ! The first multi threat program who actually runs!!!!!!!

    ReplyDelete