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:

Monday, 18 May 2009

Avoiding Temporary Objects

I was trying to find something in this very interesting book, titled "Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions" by Herb Sutter.

There was a chapter called "Temporary Objects". Curiosity got the better of me and I started reading. The book is extremely well written and the problem very well explained. Here is a summary of the Temporary Objects problem. Have a look at the book for complete details.

Consider the following peice of code:


string FindAddr( list<Employee> emps, string name )
{

for
( list<Employee>::iterator i = emps.begin();
i != emps.end();
i++ )
{

if
( *i == name )
{

return
i->addr;
}
}

return
"";
}

This short function has three unnecessary temporary objects, two subtler ones, and two red herrings.

The two more-obvious temporaries are buried in the function declaration itself:

string FindAddr( list emps, string name )

The parameters should be passed by const reference (const&) instead of by value. So they would now become const list& and const string&, respectively. Pass-by-value forces the compiler to make complete copies of both objects, which can be expensive and completely unnecessary.

The third more-obvious avoidable temporary occurs in the for loop's termination condition:

for( /*...*/ ; i != emps.end(); /*...*/ )

For most containers (including list), calling end() returns a temporary object that must be constructed and destroyed. Because the value will not change, recomputing (and reconstructing and redestroying) it on every loop iteration is both needlessly inefficient and unaesthetic. The value should be computed only once, stored in a local object, and reused.

Next, lets consider the way we increment i in the for loop:

for( /*...*/ ; i++

Postincrement is usually less efficient than preincrement because it has to remember and return its original value. An example of Postincrement implementation is as follows:


const T T::operator++(int)
{

T old( *this ); // remember our original value
++*this; // always implement postincrement
// in terms of preincrement
return old; // return our original value
}
As you can see postincrement is less efficient than preincrement. Postincrement has to do all the same work as preincrement, but in addition it also has to construct and return another object containing the original value. Since the original value is never used in the code, there is no reason to use postincrement. Preincrement should be used instead.

You can continue reading this further in chapter 6 of the book. Book details as follows:


Monday, 11 May 2009

Another Multi-Threading example with Mutex

Here is an example where we combine the previous programs to create a multi-threaded mutex based program. If you havent already seen, then please check out the Singleton class and Multi-Threading with Thread Sync.

We are going to have some .h files in this example.

Lock.h

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

#include "Mutex.h"

class
Lock
{

public
:
// Acquire the state of the semaphore
Lock ( Mutex & mutex )
:
_mutex(mutex)
{

_mutex.Acquire();
}

// Release the state of the semaphore
~Lock ()
{

_mutex.Release();
}

private
:
Mutex & _mutex;
};


#endif



Mutex.h

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

class
Mutex
{

friend class
Lock;
public
:
Mutex () { InitializeCriticalSection (& _critSection); }
~
Mutex () { DeleteCriticalSection (& _critSection); }
private
:
void
Acquire ()
{

EnterCriticalSection (& _critSection);
}

void
Release ()
{

LeaveCriticalSection (& _critSection);
}


CRITICAL_SECTION _critSection;
};


#endif



Singleton.h

#include "Lock.h"
#include "Mutex.h"

class
aSingletonClass
{

public
:
//method to get Instance of class
static aSingletonClass *getInstance( void )
{

//Note that the class is only created when this method is called first time
if(!instance_)
instance_ = new aSingletonClass;
return
instance_;
}

//method to delete Instance of class
static void deleteInstance( void )
{

if
(instance_)
delete
instance_;
instance_ = NULL; //important as this can create dead reference problems
}
void
printSomething(char *name, int count)
{

Lock guard(mutex_);
std::cout << name << " loop " << count << std::endl;
}


private
:
//variable to store the instance of singleton
static aSingletonClass *instance_;
//default constructor should be private to prevent instantiation
aSingletonClass() {};
//destructor should be made private so no one can delete this accidently
~aSingletonClass() {};
//We also need to prevent copy being created of the object
aSingletonClass(const aSingletonClass&);

Mutex mutex_;
};



Thread.cpp

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

using namespace
std;

aSingletonClass* aSingletonClass::instance_ = NULL;

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

int
main()
{

HANDLE hThreads[2];

aSingletonClass *someVar = NULL;
//Create Instance
someVar = aSingletonClass::getInstance();

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

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

aSingletonClass::getInstance()->printSomething("Func1", Count);
}

return
;
}


void
Func2(void *P)
{

int
Count;

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

aSingletonClass::getInstance()->printSomething("Func2", Count);
}

return
;
}





The Output is as follows:

Tuesday, 5 May 2009

An example of Interface class

Sometimes it is simple and helpful to define a class that does nothing but defines a standardised interface that can be used by other classes to make sure the implementation follows a standard set of input and output paramaters. Also this approach results in faster code runs and more maintainable code.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows an example of Interface class

#include<iostream>

using namespace
std;

//Shape is an Interface Class. No data and everything pure virtual
class Shape {
public
:
virtual
void Area(int length, int breadth) = 0;
virtual
void Perimeter(int length, int breadth) = 0;
//Note, no data
};

//Derived class - Inherits Shape as Public
class Rectangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


//Derived class - Inherits Shape as Public
class Triangle : public Shape {
public
:
void
Area(int length, int breadth);
void
Perimeter(int length, int breadth);
private
:
int
someData;
};


int
main()
{

Rectangle r;
Triangle t;

cout<<"\n\n";
r.Area(3,4);
r.Perimeter(3,4);

t.Area(3,4);
t.Perimeter(3,4);

cout<<"\n\n";
return
0;
}


void
Rectangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)<<endl;
}


void
Rectangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Rectangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<2 * (length + breadth)<<endl;
}


void
Triangle::Area(int length, int breadth)
{

cout<<"\nThe Area of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/2<<endl;
}


void
Triangle::Perimeter(int length, int breadth)
{

cout<<"\nThe Perimeter of Triangle for length = "<<length<<" and\
breadth = "
<<breadth<<" is "<<(length * breadth)/3<<endl;
}


In the above example, Shape class is an 'abstract class'. All the interfaces are 'pure interfaces'. It contains no data. The derived classes now have to define the interace functions.

The output is as follows: