/*----------------------------------------------------- Script for AdSense -----------------------------------------------------*/ /* */ /* Footer ----------------------------------------------- */ #footer { clear: both; text-align: center; color: #333333; } #footer .widget { margin:.5em; padding-top: 20px; font-size: 85%; line-height: 1.5em; text-align: left; } /** Page structure tweaks for layout editor wireframe */ body#layout #header { width: 750px; } -->

Friday, April 23, 2010

Thread Synchronization With Kernel Objects:1

In previous post we saw how to synchronize threads using mechanisms that allow your threads to remain in user mode. The wonderful thing about user-mode synchronization is that it is very fast.
While user-mode thread synchronization mechanisms offer great performance, they do have limitations, and for many applications they simply do not work.
1) For example, the interlocked family of functions operates only on single values and never places a thread into a wait state.
2) You can use critical sections to place a thread in a wait state, but you can use them only to synchronize threads contained within a single process.
3) You can easily get into deadlock situations with critical sections because you cannot specify a timeout value while waiting to enter the critical section.


Now lets see how we can synchornize threads using kernel objects.kernel objects are far more versatile than the user-mode mechanisms.the only bad side to kernel objects is their performance.
calling thread must transition from user mode to kernel mode. This transition is costly: it takes about 1000 CPU cycles
For thread synchronization, each of these kernel objects is said to be in a signaled or nonsignaled state. The toggling of this state is determined by rules that Microsoft has created for each object.
For example, process kernel objects are always created in the nonsignaled state. When the process terminates, the operating system automatically makes the process kernel object signaled. Once a process kernel object is signaled, it remains that way forever; its state never changes back to nonsignaled.
A process kernel object is nonsignaled while the process is running, and it becomes signaled when the process terminates.
If you want to write code that checks whether a process is still running, all you do is call a function that asks the operating system to check the process object's Boolean value.
Threads can put themselves into a wait state until an object becomes signaled.
The following kernel objects can be in a signaled or nonsignaled state:
1) Processes
2) Threads
3) Jobs
4) Files
5) Console Input
6) File change notifications
7) Events
8) Waitable timers
9) Semaphores
10) Mutexes

Wait Functions
In my previous experience application development, I was using these wait functions. there wer 6 threads for galileo receiver to run simulteneously and feed the data to the receiver input.
There are two wait functions.
1) Here's an example of how to call WaitForSingleObject with a timeout value other than INFINITE:

DWORD dw = WaitForSingleObject(hProcess, 5000);
switch
(dw) {

case
WAIT_OBJECT_0:
// The process terminated.
break;

case
WAIT_TIMEOUT:
// The process did not terminate within 5000 milliseconds.
break;

case
WAIT_FAILED:
// Bad call to function (invalid handle?)
break;
}


2) example using WaitForMultipleObjects function.

HANDLE h[3];
h[0] = hProcess1;
h[1] = hProcess2;
h[2] = hProcess3;
DWORD dw = WaitForMultipleObjects(3, h, FALSE, 5000);
switch
(dw) {
case
WAIT_FAILED:
// Bad call to function (invalid handle?)
break;

case
WAIT_TIMEOUT:
// None of the objects became signaled within 5000 milliseconds.
break;

case
WAIT_OBJECT_0 + 0:
// The process identified by h[0] (hProcess1) terminated.
break;

case
WAIT_OBJECT_0 + 1:
// The process identified by h[1] (hProcess2) terminated.
break;

case
WAIT_OBJECT_0 + 2:
// The process identified by h[2] (hProcess3) terminated.
break;
}


Source: Summary note from my diary (I learnt these concepts long back)

Read more...

Thread Synchronization in User Mode:2

Critical Sections:
A critical section is a small section of code that requires exclusive access to some shared resource before the code can execute. This is a way to have several lines of code "atomically" manipulate a resource. By atomic, I mean that the code knows that no other thread will access the resource.system will not schedule any other threads that want to access the same resource until your thread leaves the critical section.


CRITICAL_SECTION g_cs;
DWORD WINAPI ThreadFun1(PVOID pvParam)
{

while
()
{

EnterCriticalSection(&g_cs);
//......write code. do manipulation (use global resource)
LeaveCriticalSection(&g_cs);
}

return
(0);
}

DWORD WINAPI ThreadFun2(PVOID pvParam)
{

while
()
{

EnterCriticalSection(&g_cs);
//......write code. do manipulation (use global resource)
LeaveCriticalSection(&g_cs);
}

return
(0);
}


allocate a CRITICAL_SECTION data structure, g_cs, and then wrapp any code that touches the shared resource.
Notice that I passed the address of g_cs in all calls to EnterCriticalSection and LeaveCriticalSection.
CRITICAL_SECTION is defined in WinNT.h.
Normally CRITICAL_SECTION structures are allocated as global variables.
CRITICAL_SECTION structures can be allocated as local variables or dynamically allocated from a heap.
There are just two requirements. The first is that all threads that want to access the resource must know the address of the CRITICAL_SECTION structure that protects the resource. You can get this address to these threads using any mechanism you like. The second requirement is that the members within the CRITICAL_SECTION structure be initialized before any threads attempt to access the protected resource.
CRITICAL_SECTION structure is initialized by calling VOID InitializeCriticalSection(PCRITICAL_SECTION pcs);
CRITICAL_SECTION structure can be clean up by calling VOID DeleteCriticalSection(PCRITICAL_SECTION pcs);

Don't Hold Critical Sections for a Long Time
When a critical section is held for a long time, other threads might enter wait states, which will hurt your application's performance.
It's impossible to tell how much time the window procedure requires for processing the WM_SOMEMSG message—it might be a few milliseconds or a few years. During that time, no other threads can gain access to the g_s structure. It's better to write the code as follows:
SOMESTRUCT g_s;
CRITICAL_SECTION g_cs;

DWORD WINAPI SomeThread(PVOID pvParam) {

EnterCriticalSection(&g_cs);
SOMESTRUCT sTemp = g_s;
LeaveCriticalSection(&g_cs);

// Send a message to a window.
SendMessage(hwndSomeWnd, WM_SOMEMSG, &sTemp, 0);
return
(0);
}


This code saves the value in sTemp, a temporary variable. You can probably guess how long the CPU requires to execute this line—only a few CPU cycles. Immediately after the temporary variable is saved, LeaveCriticalSection is called because the global structure no longer needs to be protected.
other threads are stopped from using the g_s structure for only a few CPU cycles instead of for an unknown amount of time.

Source: Summary note from my diary.(when I learnt these concepts long back.

Read more...

Thread Synchronization in User Mode:1

All threads in the system must have access to system resources such as heaps, serial ports, files, windows, and countless others. If one thread requests exclusive access to a resource, other threads cannot get their work done.
Threads need to communicate with each other in two basic situations:
When you have multiple threads accessing a shared resource in such a way that the resource does not become corrupt
When one thread needs to notify one or more other threads that a specific task has been completed.

Windows offers many facilities to make thread synchronization easy.

atomic access: A big part of thread synchronization has to do with atomic access—a thread's ability to access a resource with the guarantee that no other thread will access that same resource at the same time. Let's look at a simple example:

// Define a global variable.
long g_x = 0;

DWORD WINAPI ThreadFunc1(PVOID pvParam) {
g_x++;
return
(0);
}


DWORD WINAPI ThreadFunc2(PVOID pvParam) {
g_x++;
return
(0);
}


MOV EAX, [g_x] ; Thread 1: Move 0 into a register.
INC EAX ; Thread 1: Increment the register to 1.

MOV EAX, [g_x] ; Thread 2: Move 0 into a register.
INC EAX ; Thread 2: Increment the register to 1.
MOV [g_x], EAX ; Thread 2: Store 1 back in g_x.

MOV [g_x], EAX ; Thread 1: Store 1 back in g_x.


If the code executes this way, the final value in g_x is 1—not 2 as you expect! This is pretty scary.
To solve the problem above, we need something simple. We need a way to guarantee that the incrementing of the value is done atomically—that is, without interruption. The interlocked family of functions provides the solution we need.

// The long variable shared by many threads
LONG g_x;



// Incorrect way to increment the long
g_x++;



// Correct way to increment the long
InterlockedExchangeAdd(&g_x, 1);


interlocked functions assert a hardware signal on the bus that prevents another CPU from accessing the same memory address.

Read more...

Wednesday, April 21, 2010

Abstract and Sealed Class

The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.


public abstract class A
{

// Class members here.
}



An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:


public abstract class A
{

public
abstract void DoWork(int i);
}




A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes prevent derivation. Because they can never be used as a base class,
A class member, method, field, property, or event, on a derived class that is overriding a virtual member of the base class can declare that member as sealed. This negates the virtual aspect of the member for any further derived class.


public class D : C
{

public
sealed override void DoWork() { }
}






Read more...

Interface and abstract 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.

An interface is a reference type that is somewhat similar to an abstract base class that consists of only abstract members. When a class derives from an interface, it must provide an implementation for all the members of the interface. A class can implement multiple interfaces even though it can derive from only a single direct base class.

An interface has the following properties:
An interface is like an abstract base class: any non-abstract type inheriting the interface must implement all its members.
An interface cannot be instantiated directly.
Interfaces can contain events, indexers, methods and properties.
Interfaces contain no implementation of methods.
Classes and structs can inherit from more than one interface.
An interface can itself inherit from multiple interfaces.



#include<iostream>

using namespace
std;

//Shape is an Interface Class. No data and everything pure virtual
class Shape {
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.

Output:
The Area of Rectangle for length = 3 and breadth = 4 is 12.
The Perimeter of Rectangle for length = 3 and breadth = 4 is 14
The Area of Triangle for length = 3 and breadth = 4 is 6
The Perimeter of Triangle for length = 3 and breadth = 4 is 4


Difference between Abstract class and Interface.
1).Interface have only signature. whereas Abstract class have signature and definition both r allow.
2). Interface have not allow modifier access. whereas Abstract class are allowed modifier access.
3).Thurogh the Interface we can create the Multiple Inheritance whereas Abstract class are not allow the Multiple Inheritance.
4).Interface is slower compare Abstract class.

Reference: Interface Entity vs. Abstract class can refer code project's article.

source:
MSDN
Advance C++ blog
Interview Corner


Read more...

Polymorphism

Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" or is characterized by the phrase "one interface, multiple methods." and it has two distinct aspects:

At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.

Base classes may define and implement virtualmethods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.


Virtual methods enable you to work with groups of related objects in a uniform way. For example, suppose you have a drawing application that enables a user to create various kinds of shapes on a drawing surface. You do not know at compile time which specific types of shapes the user will create. However, the application has to keep track of all the various types of shapes that are created, and it has to update them in response to user mouse actions. You can use polymorphism to solve this problem in two basic steps:
Create a class hierarchy in which each specific shape class derives from a common base class.
Use a virtual method to invoke the appropriate method on any derived class through a single call to the base class method.
First, create a base class called Shape, and derived classes such as Rectangle, Circle, and Triangle. Give the Shape class a virtual method called Draw, and override it in each derived class to draw the particular shape that the class represents. Create a List object and add a Circle, Triangle and Rectangle to it. To update the drawing surface, use a foreach loop to iterate through the list and call the Draw method on each Shape object in the list. Even though each object in the list has a declared type of Shape, it is the run-time type (the overridden version of the method in each derived class) that will be invoked.


public class Shape
{

// A few example members
public int X { get; private set; }
public
int Y { get; private set; }
public
int Height { get; set; }
public
int Width { get; set; }

// Virtual method
public virtual void Draw()
{

Console.WriteLine("Performing base class drawing tasks");
}
}


class
Circle : Shape
{

public
override void Draw()
{

// Code to draw a circle...
Console.WriteLine("Drawing a circle");
base.Draw();
}
}

class
Rectangle : Shape
{

public
override void Draw()
{

// Code to draw a rectangle...
Console.WriteLine("Drawing a rectangle");
base.Draw();
}
}

class
Triangle : Shape
{

public
override void Draw()
{

// Code to draw a triangle...
Console.WriteLine("Drawing a triangle");
base.Draw();
}
}


class
Program
{

static
void Main(string[] args)
{

// Polymorphism at work #1: a Rectangle, Triangle and Circle
// can all be used whereever a Shape is expected. No cast is
// required because an implicit conversion exists from a derived
// class to its base class.
System.Collections.Generic.List<Shape> shapes = new System.Collections.Generic.List<Shape>();
shapes.Add(new Rectangle());
shapes.Add(new Triangle());
shapes.Add(new Circle());

// Polymorphism at work #2: the virtual method Draw is
// invoked on each of the derived classes, not the base class.
foreach (Shape s in shapes)
{

s.Draw();
}


// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}

}




Output:
Drawing a rectangle
Performing base class drawing tasks
Drawing a triangle
Performing base class drawing tasks
Drawing a circle
Performing base class drawing tasks



Read more...

Tuesday, April 20, 2010

Pointer to Function (Alternative to switch-case)

In previous post, we have seen Function pointer. Even though a function is not a variable, it still has a physical location in memory that can be assigned to a pointer. A function's address is the entry point of the function. Because of this, a function pointer can be used to call a function

For example, in an accounting program, you may be presented with a menu that has 20 or more selections.The most common way is to use a switch statement. However, in applications that demand the highest performance, there is a better way. An array of pointers can be created with each pointer in the array containing the address of a function. The selection made by the user is decoded and is used to index into the pointer array, causing the proper function to be executed. This method can be very fast--much faster than the switch method.

However, in applications that demand the highest performance, there is a better way. An array of pointers can be created with each pointer in the array containing the address of a function. The selection made by the user is decoded and is used to index into the pointer array, causing the proper function to be executed. This method can be very fast--much faster than the switch method.


void enter(void), del(void), review(void), quit(void);
int
menu(void);

void
(*options[])(void) = {
enter,
del,
review,
quit
} ;

//Notice how the menu( ) function automatically returns the proper index into the pointer array:
int main(void)
{

int
i;

i = menu(); /* get user's choice */

(*
options[i])(); /* execute it */
return
0;

}


int
menu(void)
{

char
ch;

do
{

printf("1. Enter\n");
printf("2. Delete\n");
printf("3. Review\n");
printf("4. Quit\n");
printf("Select a number: ");
ch = getche();
printf("\n");
}
while(!strchr("1234", ch));
return
ch-49; /* convert to an integer equivalent */
}


void
enter(void)
{

printf("In enter.");
}


void
del(void)
{

printf("In del.");
}


void
review(void)
{

printf("In review.");
}


void
quit(void)
{

printf("In quit.");
exit(0);
}



The program works like this. The menu is displayed, and the user enters the number of the selection desired. Since the number is in ASCII, 49 (the decimal value of 0) is subtracted from it in order to convert it into a binary integer. This value is then returned to main( ) and is used as an index to options, the array of function pointers. Next, the call to the proper function is executed.

Using arrays of function pointers is very common, not only in interpreters and compilers but also in database programs, because often these programs provide a large number of options and efficiency is important.

Source: C++ Complete Reference.

Read more...