17 Dec 2017

Why function pointer is used in C language?

What is function Pointer?
->funtion pointer is pointer that holds the address of a function.
Why function pointers are used in C?
->function pointers are mainly used to implement callback functions.
What is callback function in C?
->callback functions are functions which are passed as argument to other functions and this passed callback function is invoked on some event.

->best example is sigaction system call. When given event/signal like alarm,SIGINT occurs,the function pointed by the pointer  is called through the function pointer in sigaction structure.example B

->another use of function pointer is generality like templates in c++.ie. with the same function pointer different
functions can be called.example A below.

/*Example A:
 same function pointer is used to call add and sub function*/
#include<stdio.h>
/*prototype here: funcPtr is function pointer taking two integers as arguments and returning an int
int (*funcPtr(int, int))
*/
/*prototype of registration function generally used to pass function pointer as argument*/
int regfunc(int (*funcPtr)(int, int), int,  int);
/*proto types of function called by function pointers*/
int add(int a, int b);
int sub(int a, int b);

/*definition of first function called through function pointer*/
int add(int a, int b)
{
        return a+b;
}
/*definition of second function called through function pointer*/
int sub(int a, int b)
{
        return b-a;
}
/*main for calling functions through function pointer */
int main()
{
        int a,b;
        a=regfunc(add,10,20);
        printf("sum is %d\n",a);

        b=regfunc(sub,10,20);
        printf("sub is %d\n",b);

        return 0;
}
/*definition of registration function that receives a funcPtr and two inta*/
int regfunc(int (*funcPtr)(int x,int y),  int x,  int y)
{
        return (*funcPtr)(x,y);
}
/*
sum is 30
sub is 10
*/

/*Example B:
->best example is sigaction system call. When given event/signal like alarm,SIGINT occurs,
the function pointed by the pointer act is called though the function pointer in sigaction structure.example B
*/
/*
struct sigaction
{
void (*sa_handler)()//address of sighandler or SIG_IGN or SIG_DEF
sigset_t sa_mask;//to block other signals
int sa_flags;
};
*/


/*
function pointer are reference to code that are passed as argument to different code. callback functions are function which are invoked on some event.
*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>


struct sigaction act;
/*call back function to be called by funcptr on alarm event*/
void sig_handler(int signo, siginfo_t *si, void *ucontext)
{
printf("Alarm signal received is:%d\n",signo);
}

int main()
{
/*intializig function pointer with func1*/
act.sa_handler=sig_handler;
act.sa_flags=SA_SIGINFO;
/*registering functon pointer to register function*/
/*ie passing functon pointer as argument to register function*/

/*Alarm event will cause call back function call through function pointer pointed by ptr act */
sigaction(SIGALRM,&act,NULL);

alarm(3);/*Now Alarm event will cause call back function call through function pointer pointed by ptr act */

/*waiting for any signal from kernel*/
pause();

/*after signal handler call back function executed*/
printf("in main again\n");
        return 0;
}

/*
Alarm signal received is:14
in main again
*/


/*
function pointer are reference to code that are passed as argument to different code. callback functions are function which are invoked on some event.
*/
#include<stdio.h>

typedef void (*funcPtr)(void);
void regfuncPtr(funcPtr myfp);
void func1();

int main()
{
/*intializig function pointer with func1*/
        funcPtr myfp=func1;
/*registering functon pointer to register function*/
/*ie passing functon pointer as argument to register function*/
        regfuncPtr(myfp);

        return 0;
}
/*defintion of register function*/
void regfuncPtr(funcPtr myfp)
{
        printf("inside regFuncPtr\n");
        (*myfp)();
}
/*definition of function to be called by function pointer*/
void func1()
{
        printf("inside func1\n");
}
/*
inside regFuncPtr
inside func1

*/

/*What is function pointer in C?
functon pointer are reference to code that are passed as argument to different code.
What is callback function in C?
callback functions are function which are invoked on some event.
*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>


/*Another example of call back function to be called by funcptr on alarm event in C language*/
void mysignalHandler(int signo)
{
printf("\n mysignalHAndler: Alarm signal received is:%d\n",signo);
}

int main()
{
signal(SIGINT,mysignalHandler);
/*create some delay*/
printf("sleeping for 10 seconds.\n");
printf("generate SIGINT by ctrl+c command: else normal exit\n");
sleep(10);

/*after signal handler call back function executed*/
printf("in main again\n");
        return 0;
}

/*
Alarm signal received is:14
in main again
*/
This page explained syntax and c linux code for :
pointer to function
function pointer
callback functions

POSIX Semaphore Implementation Example code in C on Linux

POSIX semaphore Implementation for thread synchronization.

Accept string and convert its case. If semaphore is not used chances are there that input of one thread gets converted by other thread and unwanted result.

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<string.h>

#define MAXMSGLEN 256

sem_t sem1;
char msg1[MAXMSGLEN];
char msg2[MAXMSGLEN];
sem_t sem2;

void* threadFunc1(void *arg);
void toggleCase(char *buf);

int main()
{
        pthread_t thread1;
        char argmsg1[]="Thread1: ";
        int res;
        int thNum;

        res=sem_init(&sem1,0,0);
        res=sem_init(&sem2,0,0);

        res=pthread_create(&thread1,NULL,threadFunc1,argmsg1);

        while(1)
        {
                printf("Print message to send:\n");
                fgets(msg1,MAXMSGLEN,stdin);
                sem_post(&sem1);
                /******wait for response****/
                sem_wait(&sem2);
                printf("Resp message: %s \n",msg2);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        printf("I am :%s \n",arg);
        while(1)
        {
                sem_wait(&sem1);
                strcpy(msg2,msg1);
                toggleCase(msg2);
                sem_post(&sem2);
        }
}
void toggleCase(char *str)
{
        while(*str)
        {
                if(isupper(*str))
                        *str=tolower(*str);
                else if(islower(*str))
                        *str=toupper(*str);
                str++;
        }
}
output:
   Print message to send:
   I am :Thread1:
   aaaaa
   Resp message: AAAAA
Print message to send:
   bbbbb
   Resp message: BBBBB

   Print message to send:
   CCCCC
   Resp message: ccccc

   Print message to send:
   asdfZXCV
   Resp message: ASDFzxcv

   Print message to send:

   WITHOUT sem OP is:
   -----------------=-
   Print message to send:
   I am :Thread1:
   qqqqqqqq
   Resp message:
   Print message to send:
   aaaa
   Resp message: QQQQQQqq

   Print message to send:
   ddd
   Resp message: AAAa

   Print message to send:
   aaaa
   Resp message: ddd

   Print message to send:
   ---------------------

POSIX Mutex Implementation C Program in Linux

POSIX MUTEX implementationstwo threads takes 2 strings and combined.Two thrads trying to read two strings from the user and combined it.If mutex not used then it may be that second string  may be read by other thread.Here, with mutex we are sharing the keyboard effectively.Mutex here ensures that which ever thread gets the mutex lock will read the both strings from the user keyboard.

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
pthread_mutex_t mlock;
pthread_t th1;
void *threadFunc1(void *arg);
int main()
{
        char str1[80];
        char str2[40];
        if(pthread_mutex_init(&mlock,NULL)!=0)
        {
                printf("Mutext creation failed,\n");
                exit(1);
        }
        pthread_create(&th1,NULL,threadFunc1,NULL);
        while(1)
        {
                pthread_mutex_lock(&mlock);
                printf("MAIN THREAD Enter 2 strings:\n");
                fgets(str1,40,stdin);
                fgets(str2,40,stdin);
                strcat(str1,str2);
                printf("In main Combined String is:%s\n",str1);
                        pthread_mutex_unlock(&mlock);
        }
        return 0;
}
void* threadFunc1(void *arg)
{
        char str1[80];
        char str2[80];
        while(1)
{
pthread_mutex_lock(&mlock);
        printf("thread function Enter 2 strings:\n");
        fgets(str1,40,stdin);
        fgets(str2,40,stdin);
        strcat(str1,str2);
        printf("In Thread function Combined String is:%s\n",str1);
                pthread_mutex_unlock(&mlock);
}
}
........................................................................................................................................
MAIN THREAD Enter 2 strings:
aaaa
bbbbb
In main Combined String is:aaaa
bbbbb

MAIN THREAD Enter 2 strings:
ssss sss
dddd
In main Combined String is:ssss sss
dddd

thread function Enter 2 strings:
gggg gggg
fff fff
In Thread function Combined String is:gggg gggg
fff fff

MAIN THREAD Enter 2 strings:
sdfg
hhhhj
In main Combined String is:sdfg
hhhhj

MAIN THREAD Enter 2 strings:

7 Dec 2017

Singleton Design Pattern


Intent
The Singleton pattern ensures a class has only one instance, and provides a global point of access to it.

singleton
A Singleton is an elegant way of maintaining global state, but we should always question whether we need global state. Singleton pattern offers several advantages over global variables because it does the following:
  1. Enforces that only one instance of the class can be instantiated.
  2. Allows control over the allocation and destruction of the object.
  3. Provides thread-safe access to the object's global state.
  4. Prevents the global namespace from being polluting.
Let's think about a class which has private constructor.
It becomes a class that can't be instantiated because it has private constructor.
class MyClass {
private:
 MyClass(){}
};
We need to have an instance of the class to call it, but we can't have an instance because no other class can't instantiate it. We can use the constructor from an object of type MyClass but we can never instantiate that object because no other object can use:
new MyClass();
So, we should find a way of using a static method.
Here is an example code:
#include <iostream>

using namespace std;

class Singleton
{
public:
 static Singleton *getInstance(); 

private:
 Singleton(){}
 static Singleton* instance;
};

Singleton* Singleton::instance = 0;
Singleton* Singleton::getInstance() 
{
 if(!instance) {
  instance = new Singleton();
  cout << "getInstance(): First instance\n";
  return instance;
 }
 else {
  cout << "getInstance(): previous instance\n";
  return instance;
 }
}

int main()
{
 Singleton *s1 = Singleton::getInstance();
 Singleton *s2 = Singleton::getInstance();
 return 0;
}

Output from the run:
getInstance(): First instance
getInstance(): previous instance

Singleton pattern limits the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.


We can modify the design of the code with the following constraints:
  1. We do not want the singleton by copied so that there is only one instance. This can be achieved by declaring a private copy constructor and a private assignment operator.
  2. The getInstance() method should return a reference rather than a pointer. This blocks a client from deleting the object. Also, by making destructor private, we can achieve the same effect.
The revised code looks like this:
#include <iostream>

class Singleton
{
public:
 static Singleton& getInstance(); 

private:
 Singleton() {std::cout << "Ctor\n";};
 ~Singleton() {std::cout << "Dtor\n";};
 Singleton(const Singleton&);
 const Singleton& operator=(const Singleton&);
};

Singleton& Singleton::getInstance() 
{
 static Singleton instance;
 return instance;
}

int main()
{
 Singleton &s1; = Singleton::getInstance();
 Singleton &s2; = Singleton::getInstance();
 return 0;
}


Thread Safe Singleton
The revised version is not thread safe because there could be a race condition during the initialization of the static Singleton, Singleton& Singleton::getInstance(). But we can make the method thread safe by adding a mutex lock:
Singleton& Singleton::getInstance() 
{
        Mutex mutex;
        ScopedLock(&mutex;);  // to unlock mutex on exit
 static Singleton instance;
 return instance;
}



Notes
In 2009, the authors of the original design patterns said the only pattern they would consider removing from the original list is Singleton. This is because it is essentially a way to store global data and tends to be an indicator of poor design.
There are several alternatives to the Singleton pattern:

  1. dependency injection
  2. Monostate pattern
  3. session context