Word from the Author

"One mans mistake is another mans break"
Most of the article(s) which I have posted here are based on my own personal experience. Please do not get aggravated if you disagree with what I wrote.This is just my opinion and it might not be worth much. In case you find some errors or mistakes , have any other useful information which others including myself would benefit from or if you like an article you can always post your messages and comments here.

Operator Overloading With Friends...

Some people believe that using friend functions basically disrupts the object orientation in an application giving rise to chaos and mistrust (I guess the words are a bit too harsh .)However there are scenarios in which friend functions could come in extremely handy saving both time and effort. One such example is while using operator overloading.I believe one of the least practiced or followed techniques is operator overloading.This post targets beginner to intermediate developers but if you are an experienced programmer then please feel free to post your views.This article covers how operator overloading could be achieved with friend functions

Consider a simple code scenario in which the operators '+' and '<<' are overloaded .
This is a scenario in which friend functions were used to grant access to private members ..

class class_
{
 private:
  int somenumber;
  friend class_* operator+(class_& RHS,class_& LHS);
  friend ostream& operator<<(ostream& RHS,class_& LHS);
 public:
  class_(int a):somenumber(a){}
};

class_* operator+(class_& RHS,class_& LHS)
{
  class_ *new_class =new class_(RHS.somenumber + LHS.somenumber);
  return new_class;
}


ostream& operator<<(ostream& RHS,class_& LHS)
{RHS << LHS.somenumber;}


void main()
{
class_ objA(30);
class_ objB(40);
class_ *obj = NULL;
obj = objA+objB;//Overloaded
cout << *obj;   //Overloaded
}

Using result_of Class For Managing Return Types.

I recently came across a situation in which I needed to know what a specific wrapped up function might return , after a little reading I came across the result_of Class. This simple class is nothing but short of a god gift , although boost also has an advanced version of this class but I doubt you would ever need that (At least I dont).
Anyways this class basically gives you a return type. Here is a very simple example.
Hopefully by understanding this you could construct your own examples.
Feel free to comment
 
using namespace std;
template <class type_a>
void Function_A(type_a a)
{
 std::cout << "Non Specialized";
}

char* Function_B (int a) //Parameter does nothing
{
  return "Function_B called\n";
}

template<class obj,class par>
void Analyze(obj obj_,par par_)
{
  typedef typename std::result_of<obj(par)>::type new_type;   
  cout << "Passed Parameter:" << typeid(par_).name() << "\n";
  cout << "Function Returns:" << typeid(new_type).name() << "\n"; 
}
 
int main()
{
  Analyze(Function_A<double>,2.00);
  Analyze(Function_B,12); 
}

The Norse God and C++ Singleton

In Norse Mythology Loki was considered as a God of Giants along with other powers it had the power to shift shapes and bodies , though my interest in this topic is flimsy, however while skimming through the book  Modern C++ Design , I realized that the author Andrei Alexandrescu named a well written library after this thing anyways the aim of this post is just to show you how a simple singleton is usually achieved and how it can be achieved by using the LOKI library.You can find more information about LOKI here.


Simple Singleton Without Loki
class MyClass
{
 static MyClass* Class_Address;
 public:
  int a;
    static MyClass * GetInstance()
    {
      if (Class_Address==NULL)
      {
      Class_Address = new MyClass;
      return Class_Address;
      }
      else
      {
      return Class_Address;
      }
    }
 private:
    ~MyClass(){}
};
MyClass* MyClass::Class_Address = NULL;

void main()
{
MyClass *an_inst;
an_inst = MyClass::GetInstance();
an_inst->a=12;

MyClass *an_inst2;
an_inst2 = MyClass::GetInstance();
cout << an_inst2->a; //output would be 12
}

Simple Singleton With Loki 
#include <iostream>
#include <loki/Singleton.h>  
using namespace Loki;
class MyClass
{
public:
   int a;
};

typedef SingletonHolder<MyClass,CreateUsingNew,PhoenixSingleton> myinstance;

int main()
{
    myinstance::Instance().a = 12;
    MyClass Instance2 = myinstance::Instance();
    std::cout << Instance2.a; //output is 12
    std::cin.get();
}
There are tons of ways creating a singleton without using LOKI however  the aim of this post was to introduce the LOKI library.In case you have any questions or you simply enjoyed  reading the article please leave your comments here.

Threading,Concurrency and Parallelism

All this talk about concurrency and parallelism tends to  confuse an average developer.Specially one who considers himself pretty capable in threading , at this point however he begins to have doubts about his skills and eventually begins to entertain the fact that he might be getting outdated.Well no worries the aim of this post is to calm those developers down and to explain what the above jargon really means or at least my point of view.Now both the terms concurrency and parallelism basically refer to the the behavior of a multi threaded application.

What is concurrency ?
Before defining concurrency we need to know how an operating system handles threads.In
Windows a thread is given about (3 Quantums or 10 milliseconds) of a processors time.
Now if the processor under discussion is a single processor and our multithreaded application has 2 threads then theoretically speaking each thread will be given about 10 milliseconds to work after which the CPU will shift its attention over to the other thread thus temporarily pausing the previous thread.(Practically Windows basically allows you to configure priority of background threads but that's another topic) When talking about concurrent applications we only compare the threads of that application . More details can be found here

Anyways as we already mentioned that the previous thread would be stopped and a new thread would be started.Since 10 milliseconds is a very very small interval it appears to us as if the two threads are running simultaneously.Now we know that is untrue.This behaviour is known as concurrency in which threads of an application are run by a processor one by one after intervals.


What is parallelism ?
Now suppose we are using windows in a multiprocessor environment now each thread in the multi threaded application can run on a separate processor, resulting in parallel execution, which is true simultaneous execution , thus called parallelism . When the number of threads in a process is less than or equal to the number of processors available, the operating system's thread support system ensures that each thread runs on a different processor.This is know as parallelism


Event Driven Programming C++ and Delphi

One of the first question which a firmware developer usually asks a desktop developer is about event driven programming since the embedded developer relies heavily on the Controllers ISR (Interrupt Service Routine).

In this post I am going to try to answer this question .The basic idea between event driven programming is almost the same in all programming languages such as Delphi,C++ or C#

Before getting started with an example , I would like to make it clear that there are basically two types of events in an App the first type is the Application Level Events and the other type is System Level Events. In this post I'll only cover Application Level Events.
 
Example of Creating Application Events Directly in C++
In this example whenever the value of variable "i"  in my class is less than 6 an event is triggered.

#define IMPLEMENT_SET_GET_METHOD( type , name ) \
IMPLEMENT_SET_METHOD( type , name );            \
IMPLEMENT_GET_METHOD( type , name );


#define IMPLEMENT_SET_METHOD( type , name )     \
private:                type name;              \
public:                 void set_##name( const type& value ) \
{  name = value;              \
  if(this->Function_Address)  \
  {                           \
   if(value<6){ this->Function_Address(value);}\
  }                           \
}


#define IMPLEMENT_GET_METHOD( type , name )         \
public:          const type& get_##name() const             { return name; }

void myEvent(int iNum)
{
     cout << "Number  less than 6 Event Triggered";
 
}

class MyClass
{
private:
  IMPLEMENT_SET_GET_METHOD(int,i)
  void (*Function_Address)(int);
public:
  MyClass();
  MyClass(void (*iChange)(int));
};

MyClass::MyClass()
{
  this->Function_Address = NULL;
  this->i = NULL;
}

MyClass::MyClass(void (*iChangeHandler)(int))
{
  this->Function_Address = iChangeHandler;
  this->i = 0;
}

void main(void)
{
  MyClass objMyClass(&myEvent);
  objMyClass.set_i(12);
  cin.get();
}

 
Using the Observer Pattern
Now consider the scenario changes and this time you want MyClass to trigger methods of a group of different objects what would you do ?? Well in such a case you'll have to use the observer pattern .In this pattern all the objects that are interested in a specific object  will have to attach themselves to that particular object  hence whenever there is a change in that particular object these attached objects will be informed.


Observer Pattern Example

Now Subject class here is exactly similar to MyClass above.Now if the value of a in this class is less than 6 then an alert is triggered in all of its subscribers
class Subject
{
private:
int a;
std::vector <class Observer*> subscriber;
void update();
public :
   void set_a(int val)
   {
      a = val;
              update();
   }
   void attach(Observer *add)
   {
             subscriber.push_back(add);
   }
};


class Observer
{
private:
Subject *SubjInst;
public:
int object_id;
virtual void mymethod(int id)=0;
  Observer(Subject *sub,int id)
  {
   object_id = id;
   SubjInst = sub ;
   SubjInst->attach(this);
  }
};


void Subject::update()
{
   for(int i=0;i<subscriber.size();i++)
   {
     if(a<6)
     {subscriber[i]->mymethod(subscriber[i]->object_id);}
   }
}
 
class obj1:public Observer
{
public:    
  void mymethod(int id)
  {std::cout << "Object " << id << "Informed" << "\n";}
      obj1(Subject *sub,int id):Observer(sub,id)
      {}
};

void main()
{
//Create a new Subject
Subject some_subject;
obj1 a_object(&some_subject,1);
obj1 b_object(&some_subject,2);
some_subject.set_a(1);
};

Example of Creating Application Events Directly in Delphi
My Delphi is quiet weak now since I no longer use it anymore but I thought that giving a Delphi example would enhance an understanding on events and would serve as a much better example than a plain old simple C#+= example :)

type
  Function_Prototype = procedure(Sender: TObject; Value: Integer) of Object;

  TMyClass = class(TComponent)
  private
     FValue: Integer;
     FEventName: Function_Prototype;  //Step 1:
     procedure SetValue(const AValue: Integer);
     function  GetValue(): Integer;
  public
     constructor Create(AOwner: TComponent); override;
     property Value: Integer read GetValue write SetValue;
  published
     property OnEvent: Function_Prototype read FEventName write FEventName;
  end;

implementation

procedure TMyClass.SetValue(const AValue: Integer);
begin
  FValue := AValue;
  if AValue < 6 then
  begin
    if Assigned(FEventName) then FEventName(Self, Value);
  end;
end;

function TMyClass.GetValue(): Integer;
begin
  Result := FValue;
end;
 

One Pin Communication Firmware Using CCS

I was recently asked for a project which I had worked on during my undergraduate studies. The Project involved writing a firmware through which two Microchip family based 16f877A Micro-controllers could communicate with each other using a single bidirectional port the input they received was from a serial RS-232 port (I know they are obsolete now .. however porting this project to a PIC 18F4550 for a USB interface is definitely on my to do list since i no longer work with firmware that would definitely be a welcoming change) .

The .hex file got generated using the following code
#include <16F877.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=20000000)

#use rs232(baud=9600, float_high, bits=9, xmit=PIN_B0, rcv=PIN_B0)

#define OUR_ID 1

#define MAX_MESSAGES 4
#define MAX_LENGTH   7

byte pbus_buffer[MAX_MESSAGES][MAX_LENGTH+1];
byte next_in=0;
byte next_out=0;
enum pbus_states {PBUS_IDLE=0x80,PBUS_NEED_LEN=0x81,PBUS_NEED_TO=0x82,
                  PBUS_NEED_FROM=0x83,PBUS_NEED_CS=0x84};
byte pbus_state=PBUS_IDLE;
byte checksum;
byte last_byte;

#bit ninth_bit = RS232_ERRORS.7
#bit collision = RS232_ERRORS.6
#bit intf = 11.1

#int_ext
void pbus_isr() {
    byte data;

    if(kbhit()) {

      data=getc();

      if(ninth_bit) {
         switch(pbus_state) {
           case PBUS_IDLE : if(data==0xf1)
                                pbus_state=PBUS_NEED_TO;
                            break;
           case PBUS_NEED_TO :
                            if(data==OUR_ID)
                               pbus_state=PBUS_NEED_FROM;
                            else
                               pbus_state=PBUS_IDLE;
                            checksum=data;
                            break;
           case PBUS_NEED_FROM :
                            pbus_buffer[next_in][0] = data;
                            pbus_state=PBUS_NEED_LEN;
                            checksum^=data;
                            break;
           case PBUS_NEED_LEN :
                            last_byte = data+1;
                            pbus_buffer[next_in][1] = data;
                            pbus_state=2;
                            checksum^=data;
                            break;
         }
      } else
        if(pbus_state==PBUS_NEED_CS) {
           if(checksum==data)
               next_in = (next_in+1) % MAX_MESSAGES;
           pbus_state=PBUS_IDLE;
        } else if(pbus_state<0x80) {
           pbus_buffer[next_in][pbus_state] = data;
           checksum^=data;
           if(++pbus_state>last_byte)
              pbus_state=PBUS_NEED_CS;
      }
    }
}

void pbus_send( byte * message, byte to, byte len) {
   byte checksum,i;

   retry:
      checksum=len^OUR_ID^to;
      disable_interrupts(GLOBAL);
      collision=false;
      ninth_bit=1;

      putc(0xf1);           if(collision) goto error;
      putc(to);             if(collision) goto error;
      putc(OUR_ID);         if(collision) goto error;
      putc(len);            if(collision) goto error;
      ninth_bit=0;
      for(i=1;i<=len;++i) {
        checksum^=*message;
        putc(*(message++)); if(collision) goto error;
      }
      putc(checksum);       if(collision) goto error;
      intf=false;
      enable_interrupts(GLOBAL);
      return;

   error:
      delay_ms(16);
      enable_interrupts(GLOBAL);
      goto retry;
}


#if defined( __PCB__)
#use rs232(baud=9600, xmit=PIN_A3, rcv=PIN_A2)

#elif defined(__PCM__)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)

#elif defined(__PCH__)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7)
#endif

#include <input.c>

void main() {
   byte to,len,i,msg[MAX_LENGTH];

   printf("\r\nOur unit ID is %d\r\nPress S to send.\r\n",OUR_ID);

   ext_int_edge( h_to_l );
   enable_interrupts(global);
   enable_interrupts(int_ext);

   do {
      if(next_in!=next_out) {
         printf("\r\nMessage from #%d: ",pbus_buffer[next_out][0]);
         for(i=2;i<=pbus_buffer[next_out][1]+1;++i)
           printf(" %2X",pbus_buffer[next_out][i]);
         next_out=(next_out+1) % MAX_MESSAGES;
      }

      if(kbhit())
        if(toupper(getc())=='S') {
           printf("\r\nSend to: ");
           to=gethex();
           printf("\r\nLength: ");
           len=gethex();
           for(i=0;i<len;++i) {
             printf("\r\nByte %d: ",i+1);
             msg[i]=gethex();
           }
           pbus_send(msg,to,len);
           printf("\r\nSent.");
      }

   } while (TRUE);
}

and offcourse the schematic diagram is :





Thread Synchronization C++

I recently met a developer who was complaining about the lack of  material and articles available online regarding thread synchronization . According to him either the articles were too detailed or simply too vague.
I therefore decided to give my two cents on the topic , since I seem to have some extra time on my hands these days. This topic could be very advanced and I would more than appreciate and welcome other developers to comment on this topic and if you believe I am going wrong somewhere putting me write would be worth the 25 minutes it took me to write about this topic.

Threads are synchronized using the following methods:
Events,Mutex,Semaphores and Critical Sections

The following diagram shows what each method does and how its implemented

 








Example of Using a Triggering Event:

HANDLE HEvent;
void MyFunction(void *p)
{
Start:
WaitForSingleObject ( HEvent , INFINITE );      
cout << "\n Event Triggered" ;     
goto Start;
cout << "This Line would never be called \n";
return;
}

void main()
{
cout << "Main Thread Started";
HEvent = CreateEvent(NULL,false,false,"NAME"); 
_beginthread(MyFunction,0,0);
Sleep(3000);
SetEvent(HEvent); //Make Event Block
cin.get();
}       

Example of Using a Mutex:
HANDLE hMutex; 

void threadA(void* dummy)    //Thread A Procedure
{
WaitForSingleObject(hMutex, INFINITE);  //Check if handle is in use  released ?
for(int i = 0; i < 10; i++)              
cout << "testA" << endl;  //will block other wise it will continue
ReleaseMutex(hMutex);
}

void threadB(void* dummy)
{
WaitForSingleObject(hMutex, INFINITE);
for(int i = 0; i < 10; i++)
cout << "testB" << endl;
ReleaseMutex(hMutex);
}

void main()
{
hMutex = CreateMutex(NULL, false, "fileMutex");
_beginthread(threadA,0,NULL);
_beginthread(threadB,0,NULL);
}

Example of Using a Semaphore. 
I picked and modified this example from an online source , I cant seem to find the link to that site (Apologies to the original author) but I found a trace of that code in one of my projects.You don't really find good examples of semaphores online.
 
#define MAX_SEM_COUNT 10
#define THREADCOUNT 12 //No of threads to be created

HANDLE ghSemaphore;

DWORD WINAPI ThreadProc( LPVOID );

void main()
{
  HANDLE aThread[THREADCOUNT];
  DWORD ThreadID;
  int i;

  // Create a semaphore with initial and max counts of MAX_SEM_COUNT
  ghSemaphore = CreateSemaphore(NULL,MAX_SEM_COUNT,MAX_SEM_COUNT,NULL);     

  // Create worker threads
  for( i=0; i < THREADCOUNT; i++ )
  {
    aThread[i] = CreateThread(NULL,0,ThreadProc,NULL,0,&ThreadID);
  }

  // Wait for all threads to terminate
  WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);

  // Close thread and semaphore handles
  for( i=0; i < THREADCOUNT; i++ )
    CloseHandle(aThread[i]);
    CloseHandle(ghSemaphore);
}


DWORD WINAPI ThreadProc( LPVOID lpParam )
{
  DWORD dwWaitResult;
  BOOL bContinue=TRUE;

  while(bContinue)
  {
    // Try to enter the semaphore gate.
    dwWaitResult = WaitForSingleObject(ghSemaphore,INFINITE); // zero-second time-out interval

    switch (dwWaitResult)
    {
      // The semaphore object was signaled.
      case WAIT_OBJECT_0:
        // TODO: Perform task
        printf("Thread %d: wait succeeded\n", GetCurrentThreadId());
        bContinue=FALSE;

        // Simulate thread spending time on task
        Sleep(5);

        // Release the semaphore when task is finished

        if (!ReleaseSemaphore(ghSemaphore,1,NULL) )
        {
          printf("ReleaseSemaphore error: %d\n", GetLastError());
        }
        break;

      // The semaphore was nonsignaled, so a time-out occurred.
      case WAIT_TIMEOUT:
        printf("Thread %d: wait timed out\n", GetCurrentThreadId());
        break;
    }
  }
  return TRUE;