Monday, 25 May 2009

Thread Synchronization with Events

Here is an example of using Event with multiple threads for Thread Sync.

Event.h

//Example from http://www.relisoft.com/Win32/active.html
#if !defined _EVENT_H_
#define _EVENT_H_

class
Event
{

public
:
Event ()
{

// start in non-signaled state (red light)
// auto reset after every Wait
_handle = CreateEvent (0, FALSE, FALSE, 0);
}

~
Event ()
{

CloseHandle (_handle);
}


// put into signaled state
void Release () { SetEvent (_handle); }
void
Wait ()
{

// Wait until event is in signaled (green) state
WaitForSingleObject (_handle, INFINITE);
}

operator
HANDLE () { return _handle; }

private
:
HANDLE _handle;
};


#endif



Thread.cpp

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This shows example of Multithreading, thread sync, Events
#include <windows.h>
#include <process.h>
#include <iostream>
#include "Event.h"

using namespace
std;

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

Event _event; //Create an event

int
main()
{

HANDLE hThreads[2];

//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);

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


void
Func1(void *P)
{

int
Count = 0;

for
(;;)
{

_event.Wait();
do
//This loop will only start when Event is triggered
{
cout<<"Func1: Count = "<<Count++<<endl;
}
while(Count < 10);
return
;
}


return
;
}


void
Func2(void *P)
{

for
(int i = 0; i < 10; i++)
{

cout<<"Func2: i = "<<i<<endl;
}

//Release the event so Thread1 (Func1) can start
_event.Release();
return
;
}




You can also have a look at this example here which uses Event, Mutex, etc.

The output is as follows:

No comments:

Post a Comment