State Design Pattern in C++ for a Music System

State Design pattern allows an object to change it's behavior based on its internal State.The Object will appear to change its class.
State Design Pattern in C++ to implement state machine of a Music Player System.
classes used:
MusicSystem -> is the current state context manager class.
State -> is the base class of all states classes.
OFFState -> is the concrete class derived from State.
ONState -> is the concrete class derived from State.
PAUSEDState ->is the concrete class derived from State.
Example:
#include<iostream>
using namespace std;

//current_context class
class State;
class MusicSystem
{
private:
    State *currentState;//to store current state.
   
public:
    enum statesEnum
        {
        ST_STOPPED,
        ST_PLAYING,
        ST_PAUSEDState
        };
public:
    MusicSystem();

    void stopMusic();
    void playMusic();
    void playNextTrack();
    void playPreviousTrack();
    void pauseMusic();
    void setCurrentContext(statesEnum state);
};

//abstract state class
class State
{
public:
    //MusicSystem's pointer is passed so that setCurrentState can be called.
    virtual void off(MusicSystem *ms){cout<<"Already Stopped."<<endl;}
    virtual void play(MusicSystem* ms){cout<<"Already Playing."<<endl;}
    virtual void playNextTrack(MusicSystem* ms){cout<<"Can not play Next in off/paused state."<<endl;}
    virtual void playPreviousTrack(MusicSystem* ms){cout<<"Can not play Previous in off/paused state."<<endl;}
    virtual void pause(MusicSystem* ms){cout<<"Can not Switch to pause in stopped state."<<endl;}
};
//concrete state class on
class OFFState:public State
{
public:
    void play(MusicSystem *ms);
};

//concrete state class off
class ONState:public State
{
public:
    void off(MusicSystem *ms);
    void playNextTrack(MusicSystem *ms);
    void playPreviousTrack(MusicSystem *ms);
    void pause(MusicSystem* ms);
};
//concrete class pause
class PAUSEDState:public State
{
public:
    void off(MusicSystem *ms);
    void playNextTrack(MusicSystem *ms);
    void playPreviousTrack(MusicSystem *ms);
    void play(MusicSystem* ms);
   
};

MusicSystem::MusicSystem()
{
    currentState=new OFFState;
}
void MusicSystem::stopMusic()
{
    currentState->off(this);  
}
void MusicSystem::playMusic()
{
    currentState->play(this);  
}
void MusicSystem::playNextTrack()
{
    currentState->playNextTrack(this);  
}
void MusicSystem::playPreviousTrack()
{
    currentState->playPreviousTrack(this);  
}
void MusicSystem::pauseMusic()
{
    currentState->pause(this);
}


    void OFFState::play(MusicSystem *ms)
    {
    cout<<"Turning to Play."<<endl;
    ms->setCurrentContext(MusicSystem::ST_PLAYING);
    delete this;
    }
    void ONState::off(MusicSystem *ms)
    {
    cout<<"Turning to Stopped."<<endl;
    ms->setCurrentContext(MusicSystem::ST_STOPPED);
    delete this;
    }
    void ONState::playNextTrack(MusicSystem *ms)
    {
    cout<<"Playing next track..."<<endl;
    }
    void ONState::playPreviousTrack(MusicSystem *ms)
    {
    cout<<"Playing previous track..."<<endl;
    }
    void ONState::pause(MusicSystem* ms)
    {
    cout<<"Switching to Pause."<<endl;   
    ms->setCurrentContext(MusicSystem::ST_PAUSEDState);
    }
   
    void PAUSEDState::off(MusicSystem *ms)
    {
    cout<<"Turning to Stopped."<<endl;
    ms->setCurrentContext(MusicSystem::ST_STOPPED);
    delete this;
    }
    void PAUSEDState::playNextTrack(MusicSystem *ms)
    {
    cout<<"Playing next track..."<<endl;
    }
    void PAUSEDState::playPreviousTrack(MusicSystem *ms)
    {
    cout<<"Playing previous track..."<<endl;
    }
    void PAUSEDState::play(MusicSystem* ms)
    {
    cout<<"Switching to Play."<<endl;   
    ms->setCurrentContext(MusicSystem::ST_PLAYING);
    }


void MusicSystem::setCurrentContext(statesEnum state)
    {
        if(state==ST_STOPPED)
    {
    currentState=new OFFState;
    }
    else if(state == ST_PLAYING)
    {
    currentState=new ONState();
    }
    else if(state == ST_PAUSEDState)
    {
    currentState=new PAUSEDState();
    }
    else
    {
    cout<<"Unknown state"<<endl;
    }
    }


//main
int main()
{
MusicSystem ms;

ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::pauseMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::pauseMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

return 0;
}
/*
Already Stopped.
Already Stopped.
Can not Switch to pause in stopped state.
Can not play Next in off/paused state.
Can not play Previous in off/paused state.
Turning to Play.
Already Playing.
Switching to Pause.
Playing next track...
Playing previous track...
Turning to Stopped.
Can not play Next in off/paused state.
Can not play Previous in off/paused state.
*/

Factory Method Design pattern in C++ and Abstract Factory Design pattern in CPP

"Factory Method Design pattern" is used when many derived classes are derived from a common base class and object of which derived class should be instantiated is only known at run time.
One way to achieve it by providing a static method in base class itself which returns pointer to the same base class.
When client needs to create object it calls this static method to create object of required derived class by passing type of subclass as string.And need not instantiate specific object by using subclass constructor.
Benefit of factory design pattern is that when new type is added then changes required only at one place where object is created ie only new case is added in factory method.
Intent of factory method is to provide a method to create objects, But defer the object creation to derive class based on some condition or configuration which acts like a virtual constructor. It decouples client from object creation.

Another variation of Factory pattern is "Abstract factory pattern".
In abstract factory design pattern an interface(Abstract base class) is provided to create object, But, let the subclass to decide which class to instantiate.
In example ShapeFactory is the abstract base class. And, object is created based on type passed.
Factory design pattern: We have factory that produces objects that from a particular base class.
Abstract Factory Design Pattern: We have factory that creates other factories and these factories in turn creates objects derived from other base class. Abstract factory needed when when we want to create collection of related objects and not just one object.

"Factory Method Design pattern" Implementation in C plus plus
#include<iostream>
using namespace std;

class Shape
{
public:
    virtual void whichShape()=0;
    static Shape* getShape(string s);//Factory method to create Object
};
class Rectangle:public Shape
{
public:
    void whichShape(){cout<<"Rectangle"<<endl;}
   
};
class Circle:public Shape
{
public:
    void whichShape(){cout<<"Circle"<<endl;}
   
};
Shape* Shape::getShape(string s)
{
if(s=="Rectangle")
    return new Rectangle();
if(s=="Circle")
    return new Circle();

}
int main()
{
//At run time requested type is Rectangle
Shape *s1= Shape::getShape("Rectangle");
s1->whichShape();
//At run time requested type is Circle
Shape *s2= Shape::getShape("Circle");
s2->whichShape();
return 0;
}
 //---------------------------
"Abstract Factory  Design pattern" Implementation in C++
#include<iostream>
using namespace std;

class Shape
{
public:
    virtual void whichShape()=0;
//    static Shape* getShape(string s);
};
class Rectangle:public Shape
{
public:
    void whichShape(){cout<<"Rectangle"<<endl;}
   
};
class Circle:public Shape
{
public:
    void whichShape(){cout<<"Circle"<<endl;}
   
};
class ShapeFactory
{
public:
    static Shape* getShape(string s);//Factory1
    static Shape* getEdgyShape(string s);//Factory2
    static Shape* getRoundedShape(string s);//Factory3
};
Shape* ShapeFactory::getShape(string s)
{
if(s=="Rectangle")
    return new Rectangle();
if(s=="Circle")
    return new Circle();

}
int main()
{
//At run time requested type is Rectangle
ShapeFactory* sf = new ShapeFactory();
Shape* s1 = sf->getShape("Rectangle");
s1->whichShape();
//At run time requested type is Circle
ShapeFactory* sf2 = new ShapeFactory();
Shape* s2 = sf2->getShape("Circle");
s2->whichShape();

return 0;
}
 

State Design Pattern code in C++

State Design Pattern to design a Music System in C++ language.
#include<iostream>
using namespace std;

//current_context class
class State;
class MusicSystem
{
private:
    State *currentState;
public:
    MusicSystem();

    void stopMusic();
    void playMusic();
    void playNextTrack();
    void playPreviousTrack();
    void setCurrentContext(State* s)
    {
    currentState=s;
    }
};

//abstract state class

class State
{
public:
    virtual void offState(MusicSystem *ms){cout<<"Already Stopped"<<endl;}
    virtual void onState(MusicSystem* ms){cout<<"Already Playing"<<endl;}
    virtual void playNextTrack(MusicSystem* ms){cout<<"Can not play Next in off state."<<endl;}
    virtual void playPreviousTrack(MusicSystem* ms){cout<<"Can not play Previous in off state."<<endl;}
};
//concrete state class on
class OFF:public State
{
public:
    void onState(MusicSystem *ms);
};

//concrete state class off
class ON:public State
{
public:
    void offState(MusicSystem *ms);
    void playNextTrack(MusicSystem *ms);
    void playPreviousTrack(MusicSystem *ms);
};

MusicSystem::MusicSystem()
{
    currentState=new OFF;
}
void MusicSystem::stopMusic()
{
    currentState->offState(this);   
}
void MusicSystem::playMusic()
{
    currentState->onState(this);   
}
void MusicSystem::playNextTrack()
{
    currentState->playNextTrack(this);   
}
void MusicSystem::playPreviousTrack()
{
    currentState->playPreviousTrack(this);   
}


    void OFF::onState(MusicSystem *ms)
    {
    cout<<"Turning from stopped to Play."<<endl;
    ms->setCurrentContext(new ON());
    delete this;
    }
    void ON::offState(MusicSystem *ms)
    {
    cout<<"Turning from Playing to Stopped."<<endl;
    ms->setCurrentContext(new OFF());
    delete this;
    }
    void ON::playNextTrack(MusicSystem *ms)
    {
    cout<<"Playing next track..."<<endl;
    //ms->setCurrentContext(new OFF());
    //delete this;
    }
    void ON::playPreviousTrack(MusicSystem *ms)
    {
    cout<<"Playing previous track..."<<endl;
    //ms->setCurrentContext(new OFF());
    //delete this;
    }


//main
int main()
{
MusicSystem ms;

ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::playMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

ms.MusicSystem::stopMusic();
ms.MusicSystem::playNextTrack();
ms.MusicSystem::playPreviousTrack();

return 0;
}

Message queue IPC example in C

//message queue server
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/stat.h>
#include<string.h>
#define KEY 500
struct msg
{
 long int msgtype;
 char msgfromclient[1024];
 int pid;
}msgbuf;

int main()
{
 int mqid,n,fd,m1;
 mqid=msgget(KEY,0666|IPC_CREAT);
 while(1)
 {
 msgrcv(mqid,&msgbuf,sizeof(msgbuf),1,0);
 printf("Filename from client %s\n",msgbuf.msgfromclient);

//sending requested file data to client
 fd=open(msgbuf.msgfromclient,O_RDONLY);
 n=read(fd,msgbuf.msgfromclient,1024);
 msgbuf.msgtype=msgbuf.pid;
 msgbuf.pid=getpid();
 msgsnd(mqid,&msgbuf,sizeof(msgbuf),0);
 }
return 0;
}
//client
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#define KEY 500

struct msg
{
 long int type;
 char a[1024];
 int pid;
}p,p1;
int main()
{
 int m;
 m=msgget(KEY,0);
//fill the structure to send data
 p.type=1;
 printf("\nEnter the msg");
 scanf("%s",&p.a);
 pid_t pid;
 p.pid=getpid();
 msgsnd(m,&p,sizeof(p),0);
 msgrcv(m,&p1,sizeof(p),p.pid,0);
 printf("%s",p1.a);
return 0;
}

//output:
ServerTerminal$ ./server
ClientTerminal$ ./client
Enter the msg hello.txt

ServerTerminal$ 
Filename from client hello
ClientTerminal$ ./client
contents of hello.txt

Synchronized shared memory server and client in C

Client writes  a text in shared memory.
Then server reads that and convert to upper case and write back to shared memory.
Client reads toggled text from shared memory.
//Server
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>

#define MY_KEY 1983
#define SHM_SIZE 0x1000

void toggleCase(char* buff, int cnt);

int main()
{
int semId, shmId;
char* pShm;
struct sembuf smop;

semId=semget(MY_KEY,2,0660 | IPC_CREAT);

semctl(semId,0,SETVAL,0);
semctl(semId,1,SETVAL,0);
shmId = shmget(MY_KEY, SHM_SIZE, 0660 | IPC_CREAT);

pShm=shmat(shmId,NULL,0);

while(1)
{
smop.sem_num = 0;
smop.sem_op = -1;
smop.sem_flg = 0;
semop(semId,&smop,1);

strcpy(pShm+256,pShm);
toggleCase(pShm+256, strlen(pShm+256));

smop.sem_num = 1;
smop.sem_op = 1;
smop.sem_flg = 0;
semop(semId,&smop,1);

}
return 0;
}

void toggleCase(char* buff, int cnt)
{
printf("\ntoggle\n");
int ii;
for(ii=0;ii<cnt;ii++)
{
if((buff[ii]>='A')&&(buff[ii]<='Z'))
buff[ii]+=0x20;
else if((buff[ii]>='a')&&(buff[ii]<='z'))
buff[ii]-=0x20;
}
}

//Client
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>

#define MY_KEY 1983
#define SHM_SIZE 0x1000

#define MSG_LEN 256
#define RESP_MSG_START 256

//void toggleCase(char* buff, int cnt);

int main()
{
int semId, shmId;
char* pShm;
struct sembuf smop;

semId=semget(MY_KEY,2,0);

//semctl(semId,0,SETVAL,0);
//semctl(semId,1,SETVAL,0);

shmId = shmget(MY_KEY, SHM_SIZE,0);

pShm=shmat(shmId,NULL,0);

fgets(pShm,MSG_LEN,stdin);

smop.sem_num = 0;
smop.sem_op = 1;
smop.sem_flg = 0;
semop(semId,&smop,1);

smop.sem_num = 1;
smop.sem_op = -1;
smop.sem_flg = 0;
semop(semId,&smop,1);
puts(pShm+RESP_MSG_START);
return 0;
}

//void toggleCase(char* buff, int cnt)
//{
//printf("\ntoggle\n");
//}

//terminal 1: ./server
//terminal 2: ./client
india
check
//terminal 1: 
//terminal 2:
INDIA  

Does friend function follows access specifier rule in C++

No, friend functions do not follow access specifier rules as they are not members function. Friend function declared in any access specfier can access private data of the class using object.
#include<iostream>
using namespace std;
class sample
{
private:
        int a;
private:
        void privateNormalFunction(){};
private:
        friend void f1(sample);
protected:
        void friend f2(sample);
public:
        friend void f3(sample);
};
void f1(sample s)
{
s.a=10;
cout<<"f1::a"<<s.a<<endl;
}
void f2(sample s)
{
s.a=10;
cout<<"f2::a"<<s.a<<endl;
}
void f3(sample s)
{
s.a=10;
cout<<"f3::a"<<s.a<<endl;
}
int main()
{
sample s;
f1(s);
f2(s);
f3(s);
return 0;
}                                                                                                                                               
                                                                                                                                                

Private virtual function

//Can virtual function be private?
//Suppose virtual function vf() is declared as private in base.Even though vf is overriden as public in derived compiler will throw error of private at run time. But one work around could be given to declare a virtual function as private by making main() as friend function of that class.Because friend functions can access the private members.
#include<iostream>
using namespace std;
class base
{
private:
        virtual void vf(){cout<<"base::vf"<<endl;}
//friend int main();
};
class derived:public base
{
public:
void vf(){cout<<"derved::vf;"<<endl;}
};
int main()
{
base* bp = new derived;
bp->vf();//error: ‘virtual void base::vf()’ is private

return 0;
}

Vtable, vptr content and size postmortem

#include<iostream>
using namespace std;
class EmptyClass
{};
class PolymorphicVF
{
virtual void vf(){}
};
class PolymorphicDesstructor
{
virtual ~PolymorphicDesstructor()
{
}
};
class PolymorphicPureDestructor
{
virtual ~PolymorphicPureDestructor()=0;
};
class AbstractClassWithOnePureVF
{
virtual void pvf()=0;
};

class classWithOnepureVFAnd4vf
{
virtual void vf1(){};
virtual void vf2(){};
virtual void pvf()=0;
virtual void vf3(){};
virtual void vf4(){};
};

class Base
{
public:
virtual void vf(){}
};
class SingleDerivedNoOverridevf: public Base
{
};
class SingleDerivedNoOverridevf1: public Base
{
};
class SingleDerivedNoOverridevf2AndOneDM: public Base
{
public:
    char c;
};
class SingleDerivedWithOverridevf: virtual public Base
{
public:
    void vf(){}
};
class SingleDerivedWithOverridevf1: virtual public Base
{
public:
    void vf(){}
};;
class DiamiondProblemWithNoFinalOverrider:public SingleDerivedNoOverridevf, public SingleDerivedNoOverridevf1
{
};
class DiamiondProblemWithFinalOverrider:public SingleDerivedWithOverridevf, public SingleDerivedWithOverridevf1
{
void vf(){}
};
class DiamondDerivedWithThree:public SingleDerivedWithOverridevf, public SingleDerivedWithOverridevf1, public SingleDerivedNoOverridevf1
{
void vf(){}
};
class DerivedWithThreeDifferent:public EmptyClass,public PolymorphicVF,public PolymorphicDesstructor
{};
int main()
{
cout<<"sizeof(EmptyClass)="<<sizeof(EmptyClass)<<endl;//1
cout<<"sizeof(PolymorphicVF)="<<sizeof(PolymorphicVF)<<endl;//8
cout<<"sizeof(PolymorphicDesstructor)="<<sizeof(PolymorphicDesstructor)<<endl;//8
cout<<"sizeof(PolymorphicPureDestructor)="<<sizeof(PolymorphicPureDestructor)<<endl;//8
cout<<"sizeof(AbstractClassWithOnePureVF)="<<sizeof(AbstractClassWithOnePureVF)<<endl;//8
cout<<"sizeof(classWithOnepureVFAnd4vf)="<<sizeof(classWithOnepureVFAnd4vf)<<endl;//8
cout<<"sizeof(Base with one vf)="<<sizeof(Base)<<endl;//8
cout<<"sizeof(SingleDerivedNoOverridevf)="<<sizeof(SingleDerivedNoOverridevf)<<endl;//8
cout<<"sizeof(SingleDerivedNoOverridevf2AndOneDM)="<<sizeof(SingleDerivedNoOverridevf2AndOneDM)<<endl;//16
cout<<"sizeof(SingleDerivedWithOverridevf)="<<sizeof(SingleDerivedWithOverridevf)<<endl;//8
cout<<"sizeof(DiamiondProblemWithNoFinalOverrider)="<<sizeof(DiamiondProblemWithNoFinalOverrider)<<endl;//16
cout<<"sizeof(DiamiondProblemWithFinalOverrider)="<<sizeof(DiamiondProblemWithFinalOverrider)<<endl;//16
cout<<"sizeof(DiamondDerivedWithThree)="<<sizeof(DiamondDerivedWithThree)<<endl;//24
cout<<"sizeof(DerivedWithThreeDifferent)="<<sizeof(DerivedWithThreeDifferent)<<endl;//24

return 0;
}
/*
sizeof(EmptyClass)=1
sizeof(PolymorphicVF)=8
sizeof(PolymorphicDesstructor)=8
sizeof(PolymorphicPureDestructor)=8
sizeof(AbstractClassWithOnePureVF)=8
sizeof(classWithOnepureVFAnd4vf)=8
sizeof(Base with one vf)=8
sizeof(SingleDerivedNoOverridevf)=8
sizeof(SingleDerivedNoOverridevf2AndOneDM)=16
sizeof(SingleDerivedWithOverridevf)=8
sizeof(DiamiondProblemWithNoFinalOverrider)=16
sizeof(DiamiondProblemWithFinalOverrider)=16
sizeof(DiamondDerivedWithThree)=24
sizeof(DerivedWithThreeDifferent)=16
*/

//How to check content of vtable
//compiled with command:
//g++ -fdump-class-hierarchy vtable.cpp

//vtables are taken from generated class table file by above command:
//vtable.cpp.002t.class

Class EmptyClass
   size=1 align=1
   base size=0 base align=1
EmptyClass (0x0x7fc113139d80) 0 empty
//No vtable for non polymorphic class EmptyClass

Vtable for PolymorphicVF
PolymorphicVF::_ZTV13PolymorphicVF: 3u entries
0     (int (*)(...))0
8     (int (*)(...))(& _ZTI13PolymorphicVF)
16    (int (*)(...))PolymorphicVF::vf

Class PolymorphicVF
   size=8 align=8
   base size=8 base align=8
PolymorphicVF (0x0x7fc113139de0) 0 nearly-empty
    vptr=((& PolymorphicVF::_ZTV13PolymorphicVF) + 16u)

Disadvantages of references in Cpp

References can not be re initialized. They always refer to first referent.
 Reference arithmetic is not allowed.  Operation effects on actual referent. 
#include<iostream>
using namespace std;
int main()
{
int i=10;
int& j = i;
int & k =j;

cout<<"i: "<<i<<endl;
cout<<"j: "<<j<<endl;
cout<<"k: "<<k<<endl;

cout<<"&i: "<<&i<<endl;
cout<<"&j: "<<&j<<endl;
cout<<"&k: "<<&k<<endl;

//reference once initialized can not be reinitialed. point to first referent only.
int m=10;
int n=20;
int &x=m;
cout<<"x="<<x<<endl;//10
x=n;//this is not reassignment. actually its modifying value of m using x. this can be verified taking address of m and x as both would be same.
cout<<"x="<<x<<endl;//20
cout<<"m="<<m<<endl;//m gets modified to  20 now

cout<<"&x="<<&x<<endl;//0x7fff9671caf0
cout<<"&m="<<&m<<endl;//0x7fff9671caf0

//reference arithmatic is not allowed
int a=10;
int b=20;
int& ar=a;
cout<<"a="<<a<<endl;//10
cout<<"ar="<<ar<<endl;//10
ar++;//referant gets incremented not reference
cout<<"a="<<a<<endl;//11
cout<<"ar="<<ar<<endl;//11

return 0;
}
/*
i: 10
j: 10
k: 10
&i: 0x7fffee78603c
&j: 0x7fffee78603c
&k: 0x7fffee78603c
x=10
x=20
m=20
&x=0x7fffee786040
&m=0x7fffee786040
a=10
ar=10
a=11
ar=11

*/

C program to find and replace a string in a sentence

C Program for finding a pattern in a sentence and replace it with another string.
//main string: Manoj Kumar Sahu
//string to be found and replaced: uma
//new string to be replaced with uma: UMA
//resultant string: Manoj KUMAr Sahu
#include<stdio.h>
#include<string.h>
#include<malloc.h>
char* fr(char* str, char* old, char* new)
{
int count=0, i=0;
char* ret;
int lenold = strlen(old);
int lennew = strlen(new);
for(i=0;str[i]!='\0';i++)
{
if(strstr(&str[i],old)==&str[i])
{
count=count+1;
lenold=lenold-1;
}
else{}
}
ret=(char*)malloc(i+count*(lennew-lenold));
i=0;
while(*str)
{
    //if(strstr(&str[i],old)=&str[i])//l value required
    if(strstr(str,old)==str)
    {
    //copy
    strcpy(&ret[i],new);
    i=i+lennew;
    str=str+lenold;
    }
    else
    {
    ret[i]=*str;
    i++;   
    str++;
    }
}
return ret;
}
int main()
{
char str[]="manoj kumar sahu";
char old[]="uma";
char new[]="UMA";
char *result=fr(str,old,new);
printf("resltanc string=%s\n",result);
return 0;
}

Multiple Inheritance aptitude questions.Diamond problem

#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:public A
{
};
class C:public A
{
};
class D:public B, public C
{
};
int main()
{
D d;
//d.f();//error: request for member ‘f’ is ambiguous//candidates are A::f and A::f
//d.A::f();//error: ‘A’ is an ambiguous base of ‘D’
d.B::f();//A::f
d.C::f();//A::f
//d.D::f();// error: request for member ‘f’ is ambiguous
cout<<""<<endl;
return 0;
}

//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:virtual public A
{
};
class C:virtual public A
{
};
class D:public B, public C
{
};
int main()
{
D d;
d.f();//A::f
d.A::f();//A::f
d.B::f();//A::f
d.C::f();//A::f
d.D::f();//A::f
cout<<""<<endl;
return 0;
}

//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:public A
{
public:
 void f(){cout<<"B::f"<<endl;}
};
class C:public A
{
public:
 void f(){cout<<"C::f"<<endl;}
};
class D:public B, public C
{
public:
 void f(){cout<<"D::f"<<endl;}
};
int main()
{
D d;
d.f();//D::f
//d.A::f();//error: ‘A’ is an ambiguous base of ‘D’
d.B::f();//B::f
d.C::f();//C::f
d.D::f();//D::f
cout<<""<<endl;
return 0;
}

//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:virtual public A
{
public:
 void f(){cout<<"B::f"<<endl;}
};
class C:virtual public A
{
public:
 void f(){cout<<"C::f"<<endl;}
};
class D:public B, public C
{
public:
 void f(){cout<<"D::f"<<endl;}
};
int main()
{
D d;
d.f();//D::f
d.A::f();//A::f
d.B::f();//B::f
d.C::f();//C::f
d.D::f();//D::f
cout<<""<<endl;
return 0;
}
//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:public A
{
public:
 void f(){cout<<"B::f"<<endl;}
};
class C:public A
{
public:
 void f(){cout<<"C::f"<<endl;}
};
class D:public B, public C
{
};
int main()
{
D d;
//d.f();//error: request for member ‘f’ is ambiguous//candidates are A::f and C::f and B::f
//d.A::f();//error: ‘A’ is an ambiguous base of ‘D’
d.B::f();//B::f
d.C::f();//C::f
//d.D::f();// error: request for member ‘f’ is ambiguous//candidates are A::f C::f and B::f
cout<<""<<endl;
return 0;
}
//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:virtual public A
{
public:
 void f(){cout<<"B::f"<<endl;}
};
class C:virtual public A
{
public:
 void f(){cout<<"C::f"<<endl;}
};
class D:public B, public C
{
};
int main()
{
D d;
//d.f();//error: request for member ‘f’ is ambiguous
d.A::f();//A::f
d.B::f();//B::f
d.C::f();//A::f
//d.D::f();//error: request for member ‘f’ is ambiguous
cout<<""<<endl;
return 0;
}
//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:public A
{
public:
 void f(){cout<<"B::f"<<endl;}
};
class C:public A
{
};
class D:public B, public C
{
};
int main()
{
D d;
//d.f();//error: request for member ‘f’ is ambiguous//candidates are B::f and A::f
//d.A::f();//error: ‘A’ is an ambiguous base of ‘D’
d.B::f();//B::f
d.C::f();//A::f
//d.D::f();// error: request for member ‘f’ is ambiguous//candidates are A::f and B::f
cout<<""<<endl;
return 0;
}
//--
#include<iostream>
using namespace std;

class A
{
public:
 void f(){cout<<"A::f"<<endl;}
};

class B:virtual public A
{
public:
 void f(){cout<<"B::f"<<endl;}
};
class C:virtual public A
{
};
class D:public B, public C
{
};
int main()
{
D d;
d.f();//B::f
d.A::f();//A::f
d.B::f();//B::f
d.C::f();//A::f
d.D::f();// B::f
cout<<""<<endl;
return 0;
}

Remove consecutive repeated characters from a string.

//C program to remove consecutive repeated characters from string.
//C program to remove consecutive repeated elements from an array.

#include <stdio.h>
#include<string.h>
int main()
{

int i,j,len,len1;
char str[100];
printf("Enter a string with repeated adjacent characters:");
gets(str);
    len=strlen(str);

    //assign 0 to len1 - length of removed characters
    len1=0;

    //Removing consecutive repeated characters from string
    for(i=0; i<(len-len1);)
    {
        if(str[i]==str[i+1])
        {
            //shift all characters
            for(j=i;j<(len-len1);j++)
                str[j]=str[j+1];
            len1++;
        }
        else
        {
            i++;
        }
    }

    printf("String after removing duplicate adjacent elements : %s\n",str);

    return 0;
}
/*
Enter a string with repeated adjacent characters:abbcccdefabc
String after removing duplicate adjacent elements : abcdefabc
*/
//Removing consecutive members in an array
#include<iostream>
using namespace std;

class Base
{

};
void print(int* p)
{
while(*p)
cout<<*p++<<" ";
cout<<endl;
};
int main()
{
cout<<""<<endl;
int arr[]={1,2,2,3,3,2,4,5,5,55,555,5};

print(arr);
int size=sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;)
{
if(arr[j]==arr[j+1])
{
for(int k=j;k<size;k++)
{
arr[k]=arr[k+1];
}
//shift
size--;
}
else
{
//check next
j++;
}
}
}
print(arr);
return 0;
}
/*
1 2 2 3 3 2 4 5 5 55 555 5
1 2 3 2 4 5 55 555 5
*/

C program to find only unique elements of array

//C++ Program to find only unique elements in array of integers.
using namespace std;
#include <stdio.h>
#include <string.h>
//#include <stdlib.h>
int main() {
   int arr[20], i, j, k, size;

   printf("\nEnter the size of the array : ");
   scanf("%d", &size);

   printf("\nEnter the Numbers in array : ");
   for (i = 0; i < size; i++)
      scanf("%d", &arr[i]);

   printf("\nArray with Unique elements is  : ");
   for (i = 0; i < size; i++) {
      for (j = i + 1; j < size;) {
         if (arr[j] == arr[i]) {
            for (k = j; k < size; k++) {
               arr[k] = arr[k + 1];
            }
            size--;
         } else
         {
            j++;
         }
      }
   }

   for (i = 0; i < size; i++) {
      printf("%d ", arr[i]);
   }
    printf("\n");
   return (0);
}
/*
Enter the size of the array : 8
Enter the Numbers in array :
1
2
2
3
4
2
3
1
Array with Unique elements is  : 1 2 3 4
*/
//C Program to remove all duplicate elements from an array
#include<iostream>
using namespace std;

class Base
{

};
void print(int* p)
{
while(*p)
cout<<*p++<<" ";
cout<<endl;
};
int main()
{
cout<<""<<endl;
int arr[]={1,2,2,3,3,2,4,5,5,55,555,5};

print(arr);
int size=sizeof(arr)/sizeof(arr[0]);
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;)
{
if(arr[i]==arr[j])
{
for(int k=j;k<size;k++)
{
arr[k]=arr[k+1];
}
//shift
size--;
}
else
{
//check next
j++;
}
}
}
print(arr);
return 0;
}
/*
1 2 2 3 3 2 4 5 5 55 555 5
1 2 3 4 5 55 555
*/

CMakeLists.txt and cmake interview questions

What is a cmake?
cmake is a cross platform open source software for managing build system of a software. It generates native makefile which is the recipe file for native make tool to create any application in Linux. It is also used with other native build environments such as make Apple's Xcode, and Microsoft Visual Studio.
It supports directory hierarchies. Each directory contains a CMakeLists.txt file.
It supports applications that depends on multiple libraries.
What is CMakeLists.txt?
CMakeLists.txt file contains instruction to "cmake" tool to generate a native Makefile which the instructions file for "make" to create an application.

A Simple multi folder camke project example say MyProject.Simple cmake demo example can be found here.
MyProject
├── CMakeLists.txt
├── myapp
│   ├── CMakeLists.txt
│   └── main.cpp
└── mylibs
    ├── CMakeLists.txt
    ├── mylib.cpp
    └── mylib.h
 

Top most MyProject/CMakeList.txt
cmake_minimum_required(VERSION 2.8)
add_subdirectory(mylibs)
add_subdirectory(myapp)

myapp/CMakeLists.txt
add_executable(app main.cpp)
target_link_libraries(app mylib)

myapp/main.cpp
#include<iostream>
using namespace std;
#include "../mylibs/mylib.h"
int main()
{
cout<<"main"<<endl;
libfun1();
libfun2();
return 0;
}

mylibs/CMakeLists.txt
add_library(mylib mylib.cpp)

mylib/mylib.cpp
#include<iostream>
using namespace std;
void libfun1()
{
cout<<"libfun1"<<endl;
}
void libfun2()
{
cout<<"libfun2"<<endl;
}

mylib/mylib.h
void libfun1();
void libfun2();

How to build in a separate direcory
cd MyProject
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX:PATH=/tmp/foo
make
make install.
Summary:
    Using CMake with executables
    add_executable(myapp main.c)

    Using CMake with static libraries
    add_library(test STATIC test.c)

    Using CMake with dynamic libraries
    add_library(test SHARED test.c)

    Linking libraries to executables with CMake
    add_subdirectory(libtest_project)
    add_executable(myapp main.c)
    target_link_libraries(myapp test)

Frequently asked thread questions in C Linux

Q)When should thread be used?
Threading could be used in operations required like:
i)Asynchronous operations
ii)Operations that can be parallelized
iii)Continual running background operations
Q)What is Asynchronous operations?
A synchronous operation blocks a process till the operation completes. 
An asynchronous operation is non-blocking and only initiates the operation. The caller could discover completion by some other mechanism.
Q)What are the difference between a mutex and a semaphore?
i)Mutex as the name suggests is used for mutually exclusive usage of shared resource by any one thread at a time. ii)The thread which has locked the mutex that only can release the lock. While in case of semaphore this not so.
i) In case of semaphore specified numbers of threads can use the shared resource simultaneously. ii)Also It is not necessary that the locking thread only release the lock. It can be released by any thread.
Q) What is the difference between a binary semaphore and a mutex.?
In case of a mutex the thread which has locked the mutex that only can release the lock. While in case of semaphore this is not so. It is not necessary that the locking thread only release the lock. It can be released by any thread.
Q) What is POSIX?
Portable Operating System Interface. Posix is standarad based thread API's for C and C++. It provides APIs for thread creation,termination,synchronization(join,blocking), data management,scheduling and process interaction.
Q) What is thread and why it is used?
Threads are function under execution. Threads are used to make software more responsive and faster by introducing parallelism through multiple process. Thread shows better result in multi core system as single processor machines run as single threaded application and scheduling between threads are so fast that it appears fast.
Q) Why threads are fast?
Threads are faster to create and terminate as threads share data segment of the process and they run on the same address space of the process.
Unlike threads process creation(forking) involves creation of different address spaces different apllications.
Two threads of same process share:
Data segment(global and static variable as these are stored in data segment).
Address space of the process.
Open file's file descriptor.
Current Directory
User and Group Id
Signal and signal handlers
Threads have unique or their own thread Ids:
Thread Id.
Stack, local variables and register
Program counter and return values like errno
priority
signal mask
Q) What is the syntax of a thread:
int pthread_create(pthread_t* thread, //pointer to the thread so call should pass address of the thread
                       const pthread_attr_t * attr,// PTHREAD_CREATE_JOINABLE is default also PTHREAD_CREATE_DETACHED
                       void* (*start_routine)(void *), //pointer to the function to be threaded.Function has a single argument:pointer to void
                       void* arg);//pointer to argument of function. To pass multiple arguments, send a pointer to a structure.

Q)What is the return type of thread_crate api?
pthread_create return the thread id on success and 0 on error while creating thread.
Q) What is the default attribute to the thread?
NULL ie default attribut which is joinable PTHREAD_CREATE_JOINABLE. other attribute can be set is  PTHREAD_CREATE_DETACHED.
Q) What is the last argument of create_thread attribute?
Last argument in thread is pointer to the argument of the function.
Q) How to pass multiple arguments to thread?
Pointer to structure can be used to pass multiple arguments to a thread in pthread_create api.
Q) What api is used to get thread id?
pthread_self();
Q) What does int pthread_join(pthread_t th, void **thread_return); does?
pthread_join makes the calling thread to waits till specified thread gets terminated or completed.
Q) What is the use of void pthread_exit(void *retval);?
pthread_exit terminates/kills the calling thread.
Q)How to check pthread_exit has killed/terminated the calling thread or not?
take the return value of api like int=pthread_exit(); it works on C and not in C++ as void return type of pthread exit.
Q)How to check pthread_create is successfull or not?
take the return value of api like int=pthread_create(); if 0 then failure else thread_id is returned. instead of int use unsigned long int.
Q) How Thread synchronization is achieved?
Using Mutex,condtion variables and joins.
Mutex: are used for mutual exclusive usage of global variables by any single thread at a time.
Conditional variables: are variable of type pthread_cond_t used with mutex to achieve atomic use of global variable and to avoid race condition
join: Join suspends the calling thread till specified thread completes its task. Join is used when it wants to wait for thread/threads it has created to get terminated/completed.
Q) What is race condition?
Race condition occurs when mutiple threads modifies the global variable but the result of the computation depends on the order of in which these threads perform on the shared global variable. Mutex are used to protect the critical section of a thread so that global variable can be used in protected manner by only one thread at a time.
//Without mutex
int counter=0;
void function1()
{
   counter++ //thread1 and thread2 both can modify and inconsistent result when any of the thread stores the modified value to their local register.
}
//With mutex
int counter=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;;
void function1()
{
pthread_mutex_lock(&mutex);
   counter++ //thread which has mutex that only can modify counter so blocking. so use condition variable.
pthread_mutex_unlock(&mutex);
}
Q) What is Condition variable and When it should be used?
Condition variable is a variable of type pthread_cond_t which is used with mutex for thread synchronization/serialization.
Condition variable allows a thread to suspend or release the processor till a condition is true. Condition variable must be used with mutex to avoid deadlock crated by thread by locking  it when other thread may wait for global variable to get ulocked.Conditional variable is used for signaling like hey I am done with my task with shared resource you may use it now.
Condition variable uses signal and wait mechanism to avoid deadlock situation.
Creating/Destroying:
   pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
   pthread_cond_init
   pthread_cond_destroy
Waiting on condition:
        pthread_cond_wait - unlocks the mutex and waits for the condition variable cond to be signaled.
        pthread_cond_timedwait - place limit on how long it will block.
Waking thread based on condition:
        pthread_cond_signal - restarts one of the threads that are waiting on the condition variable cond.
        pthread_cond_broadcast - wake up all threads blocked by the specified condition variable.
// Pthread example code in C++ with and without synchronization
//Thread example in C++. One thread should prints odd numbers and the other thread should print the even numbers. Example without synchronization.
#include<iostream>
using namespace std;
int count=0; //global variable accessed by two threads
int maxx=10;
void* even(void *v)
{
cout<<"even thread"<<endl;
while(count<maxx)
{
if((count%2)==0)
{
cout<<count++<<" ";
//count++;
}
}
pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
cout<<"odd thread"<<endl;
while(count<maxx)
{
if((count%2)==1)
{
cout<<count++<<" ";
//count++;// then proper order :)
}
}
pthread_exit(0);
}

int main()
{
pthread_t t1;
pthread_t t2;

pthread_create(&t1,NULL,&even,NULL);
pthread_create(&t2,NULL,&odd,NULL);
pthread_join(t1,0);
pthread_join(t2,0);
//pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
cout<<endl;
return 0;
}
//OUTPUT
~$ g++ test1.cpp -lpthread
~$ ./a.out
even thread
0 odd thread
1 3 2 5 4 76  89
//Improved Example synchronized using mutex and conditional variable.
#include<iostream>
using namespace std;
int count=0;
int maxx=10;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* even(void *v)
{
    //cout<<"even thread"<<endl;
    while(count<maxx)
    {
        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)==0)
        {
            pthread_cond_wait(&cond,&mutex);
            //it releases the mutex and it waits till condition cond is signaled as complete and mutex is available.
        }
        cout<<"even "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);// restarts one of the threads that are waiting on the condition variable cond.
    }
    pthread_exit(0);//pthread_exit is called from the thread itself to terminate its execution (and return a result) early.
}
void* odd(void *o)
{
    while(count<maxx)
    {

        pthread_mutex_lock(&mutex);//lock before checking
        while((count%2)==1)
        {
            pthread_cond_wait(&cond,&mutex);//wait until count becomes odd
        }
        cout<<"odd "<<count++<<endl;
        pthread_mutex_unlock(&mutex);//release
        pthread_cond_signal(&cond);//signal to another thread
    }
    pthread_exit(0);
}
int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex, 0);
    pthread_cond_init(&cond, 0);

    pthread_create(&t1,NULL,&even,NULL);
    pthread_create(&t2,NULL,&odd,NULL);
    pthread_join(t1,0);
    pthread_join(t2,0);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    //pthread_join is called from another thread to wait for a thread to terminate and obtain its return value
    cout<<endl;
    return 0;
}
/*
odd 0
even1
odd 2
even3
odd 4
even5
odd 6
even7
odd 9
even10
*/
http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html
http://www.bogotobogo.com/cplusplus/quiz_multithreading.php
https://linuxtrainers.wordpress.com/2014/12/22/importance-of-pthread-condition-variables/

Q) What are the common pitfalls in threading?
race condition, deadlock, no thread safe code.

Q) Race condition: As the threads are scheduled by OS so order is not fixed so unexpected result of computation on global variable by multiple threads. So mutex, join and condition variable must be used to achieve the proper order of function calling.
Q) Dead lock: Deadlock occurs when one thread lock and mutex and not unlock it. Deadlock may also occur when a thread lock a mutex and other threads trying lock mutex fails eventually thread will goes into locking mutex for ever so proper order of mutex lock and join must be used.
Q) Thread safety: A code is called thread safe when either it does not have global and static variable if there then mutex and join must be used.

Q) What is race condition?
Race condition is a bug in a multithreaded application. Race condition occurs when two or more threads access the same memory location like global variables simueltaneously. Suppose one global variable x is there which is modified by two threads t1 and t2 simueltaneously. Thread t1 modifies the global and saves in register variable again and again Similarly thread t2 modifies the global variable and stores the modified variable in local register vairble. When control goes out of threads the golbal is variable's value becomes unpredictable. So to protect global variable/ resource or to avoid race conditions mutex or locks are used.

Q) What is mutex?
Mutex or mutual exclusion is used for thread synchronization. Along with condtion variable mutex_wait and mutex_signal are used for pprotected access of global variable. So,mutex are locking mechanism which is used for thread synchronization to avoid race condition or to avoid global variable from simueltaneous access by two or more threads.
http://thispointer.com/c11-multithreading-part-5-using-mutex-to-fix-race-conditions/

Q) What is semaphore and what is the difference between mutex and semaphor?
Semaphore is a positive counter that can be either incremented or decremented. Semaphore is used for thread syncronization using sem_wait and sem_post.Semaphore is used when there is limited resource and need some mechanism to controll its uses. Suppose there are five chairs inside a meeting room and 10 peoples inside the room. So who will seat can be conrolled using 5 tokens. A person which has a token can seat into a chair. When 5 persons seating in chair counter is set to 0. When a person releases a chair counter is increased by one. Now one token is available so one person can seat again in chair and token count is decremented and made to 0.
So, what is the difference between mutex and semaphore?
Mutex follow ownership. the thread which locks the mutext, that thread only can release the lock.
In semaphore ownership of lock is not there. Any thread can release the lock. In above example any chair can be vaccated.

Q) What is condition variable and when it is necessary?
Condition variables are like event used between two or more threads for signals. One or more threads can wait on it to get signaled, while another thread can signal it. Mutex is required along with conditional variables.
It is mandatory to make the threads non blocking.

So, How things actually work with condition variable?
Thread 1 acquires the mutex and check if required condition is met or not.
If not then it releases the lock and waits for Condition Variable to get signaled ( thread gets blocked). Condition Variable’s wait() function provides both these operations in atomic manner.
Another Thread i.e. like Thread 2 signals the Condition Variable when condition is met
Once Conditional Variable get signaled the the Thread 1 which was waiting for it resumes. It then acquires the mutex lock again and checks if the condition associated with Condition Variable is actually met or if it is superiors call. If more than one thread was waiting then notify_one will unblock only one thread.
If it was a superiors call then it again calls the wait() function.


For example two threads has to modify a global variable count to print odd and even numbers respectively.
Thread one can lock the variable count does the operations to print odd and signals to thread two, while thread two waits till the variable become even and get signaled by thread one.
Thread one signals when value of count becomes even and then thread two prints the even numbers.
Example 2:
Suppose an application has to perform 3 tasks:
1: perform handshake to server.
2: wait to read data from a xml.
3: process the data.
Multithreading approach of above application would be like below:
Task1 is not dependent on other task.But,task2 and task3 are dependent to each other.
So, Task1 and Task2 can run paralelly to improve the performance.
So One thread can do
1: perform handshake to server.
2: wait to read data from a xml.
3: process the data.
Thread 2 can d:
2: wait to read from a xml
3:Notify other thread when data is available.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int MAX = 10;
int count = 0;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *even(void *arg)
{
    while(count < MAX) {
        pthread_mutex_lock(&mutex;);
        while(count % 2 != 0) { //if odd number then enter into wait(lock also releasaed by mutex) else print the even number, unlock and                     //signal the other thread
            pthread_cond_wait(&cond;, &mutex;);
        }
        printf("%d ", count++);
        pthread_mutex_unlock(&mutex;);
        pthread_cond_signal(&cond;);
    }
    pthread_exit(0);
}

void *odd(void *arg)
{
    while(count < MAX) {
        pthread_mutex_lock(&mutex;);
        while(count % 2 != 1) {
            pthread_cond_wait(&cond;, &mutex;);
        }
        printf("%d ", count++);
        pthread_mutex_unlock(&mutex;);
        pthread_cond_signal(&cond;);
    }
    pthread_exit(0);
}

int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex;, 0);
    pthread_cond_init(&cond;, 0);

    pthread_create(&t1;, 0, &even;, NULL);
    pthread_create(&t2;, 0, &odd;, NULL);

    pthread_join(t1, 0);
    pthread_join(t2, 0);

    pthread_mutex_destroy(&mutex;);
    pthread_cond_destroy(&cond;);

    return  0;
}
The output looks like this:

0 1 2 3 4 5 6 7 8 9 10
http://www.bogotobogo.com/cplusplus/quiz_multithreading.php

// for even() thread function
pthread_mutex_lock(&mutex;);       (lock before checking)
check
   wait until count becomes even  (pthread_cond_wait(&cond;, &mutex;)
                                   - wait for signal from another thread)
do something                      (print and count++)

pthread_mutex_unlock(&mutex;);     (release)
pthread_cond_signal(&cond;);       (signal to another thread)

Q) Can two threads share the mutex?
Yes.
Q) Can two threads share the critical section?
No.
Q) What is critical section?
Critical section is section of code that modifies the global variable. Critical section code of any thread shoud be executed atomically only by one thread at a time else race condition occurs and global variable shows inconsistant value as threads modify and save the variables in their local registers.
Q) What is race condition?
A Condition when two or more thread tries to access a global variable simuetaneously. mutex or semaphore are used for protected access of global variable and avoid race condition.
Q) What is context switching?
Context switching means cpu swithcing between different processes or threads. In a single CPU system all processes or threads gets cpu time in round robin fashion. In multi core system if n cores then n processes can run independently.

CMakeLists.txt and cmake interview questions

STLSet all operation example code in C++ Linux

Set is an associated template container. Only values are stored in set.Once value inserted can not be modified.If want to modify then first erase then modify. In map using at() or [] we can directly insert new value. Values are stored in sorted ascending order. Effect of inserting a duplicate value does nothing.
#include<iostream>
using namespace std;
#include<set>
#include<algorithm>
int main()
{
cout<<"Creating an empty set:"<<endl;
set<int> set;
cout<<"Inserting into a set"<<endl;
set.insert(11);
set.insert(33);
set.insert(22);
set.insert(55);
set.insert(44);//does nothing
set.insert(44);//does nothing
set.insert(44);//does nothing

cout<<"iTraversing through into a set"<<endl;
std::set<int>::iterator itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";

cout<<"Searching in a set"<<endl;
itr=set.begin();
itr=set.find(55);
if(itr!=set.end())
cout<<"55 found"<<endl;
else
cout<<"55 not found"<<endl;

cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";


cout<<"finding and deleting from a set"<<endl;
itr=set.begin();
itr=set.find(22);
if(itr!=set.end())
{
cout<<"22 found"<<endl;
set.erase(22);
//itr=set.erase(22);//change to other itr2
}
else
{
cout<<"22 not found"<<endl;
}

set.erase(22);//deleting again no effect
cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";


cout<<"Deleting a range"<<endl;
std::set<int>::iterator itr2=set.begin();
std::set<int>::iterator itr3=set.end();
set.erase(itr2,itr3);

cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";

cout<<""<<endl;
return 0;
}
/*
Creating an empty set:
Inserting into a set
iTraversing through into a set
11 22 33 44 55 Searching in a set
55 found
Traversing
11 22 33 44 55 finding and deleting from a set
22 found
Traversing
11 33 44 55 Deleting a range
Traversing

*/

C++ list example. All operations.

#include<iostream>
using namespace std;
#include<list>
#include<algorithm>

int main()
{
//creating an empty list
list<int> l;
//Way:1 to insert
l.push_back(10);
l.push_back(100);
l.push_back(20);
//Way:2 to insert

list<int>::iterator itr=l.begin();
while(itr!=l.end())
{
cout<<*itr<<"\t";
itr++;
}

cout<<""<<endl;
//Way:2 creating a list with fixed size 5
list<string> ls2(5);
list<string>::iterator itr2=ls2.begin();
while(itr2!=ls2.end())
{
cout<<*itr2<<"\t";
itr2++;
}

cout<<""<<endl;
//Way:2 creating a list with fixed size 5 with initial value "Mr"
list<string> ls3(5,"Mr");
list<string>::iterator itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<""<<endl;

ls3.push_back("Mr");
ls3.push_back("Mr");
ls3.push_back("Mrs");
ls3.push_back("Miss");
ls3.push_back("Mrs");

cout<<"Way 0: to remove by value"<<endl;
ls3.remove("Mr");//deletes all a value "Mr"
itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}


itr3=ls3.begin();
cout<<"Way 1: to erase single value by itr"<<endl;
list<string>::iterator itr4=ls3.begin();
itr3=ls3.erase(itr4);//1th element deleted
itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<"\nWay 2: to erase range by iterator"<<endl;
itr3=ls3.begin();
list<string>::iterator itr5=ls3.begin();
list<string>::iterator itr6=ls3.end();
itr3=ls3.erase(itr5,itr6);//deletes begin to end
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<""<<endl;

return 0;
}
/*
10      100     20     
Mr      Mr      Mr      Mr      Mr     
Way 0: to remove by value
Mrs     Miss    Mrs     Way 1: to erase single value by itr
Miss    Mrs    
Way 2: to erase range by iterator
*/

make and makefile interview questions

Source code can be found here .
 Just download or clone and build by running command "make".
Q)What is make?
->make is a build automation tool that automatically build executables and libraries by reading a file called Makefile which tells the make how to compile and link a program.
Q)What is a makefile?
Makefile is the recipe(rule to build) file, which tells the build automation tool "make" how to compile and link.
Q)What does a makefile contains?
A makefile mainly contains directives(rules) like target,dependency and and rule. It also contains "set" directive to set a variable and comments, statements stating with a #.
Syntax of a makefile:
target: dependencies
[ a tab ]recipe (system commands)

Where: target, is name of the executable(binary),object file or any action like "clean".
dependency, is the input files required to create the binary and
recipe, are the system commands that make carries out.
Q)What is the difference between makefile and Makefile?
Order of execution is the difference.
If for execution "make" is not given "-f" option then it first looks for a file "makefile" then "Makefile".
If for execution "make" is given "-f" option then it first looks for a file "Makefile" then "makefile".

A simple example of makefile:
hello: main.o factorial.o hello.o
g++ main.o factorial.o hello.o -o hello
main.o: main.cpp functions.h
g++ -c main.cpp
factorial.o: factorial.cpp functions.h
g++ -c factorial.cpp
hello.o: hello.cpp functions.h
g++ -c hello.cpp
clean:
-rm *.o
---------------------------
code:
//main.cpp
#include <iostream>
using namespace std;
#include "functions.h"

int main(){
   print_hello();
   cout << endl;
   cout << "The factorial of 5 is " << factorial(5) << endl;
   return 0;
}

//functions.h
void print_hello();
int factorial(int n);

//functions.cpp
#include "functions.h"
int factorial(int n){
   if(n!=1){
      return(n * factorial(n-1));
   }
   else return 1;
}
//hello.cpp
#include <iostream>
using namespace std;
#include "functions.h"
void print_hello(){
   cout << "Hello World!";
}

CMakeLists.txt and cmake interview questions