posix_semaphore

Document Sample
posix_semaphore Powered By Docstoc
					Synchronizing Threads with POSIX Semaphores
Posix semaphores defined in             < semaphore.h.>

          sem_init :initialize semaphore
          sem_wait: to wait on semaphore & decrements semaphore        count by 1.
          sem_post : to increases the semaphore count by 1
          sem_getvalue : Stores the count of the semaphore to sval
          sem_destroy : Destroys the semaphore object


POSIX semaphores
All POSIX semaphore functions and types are prototyped or defined in <semaphore.h>
To define a semaphore object ,use :
        sem_t sem_name;

To initialize a semaphore, use sem_init():
           int sem_init(sem_t *sem, int pshared, unsigned int value);

sem: points to a semaphore object to initialize
pshared: is a flag indicating whether or not the semaphore should be
shared with fork()ed processes. LinuxThreads does not currently support
shared semaphores.Hence should pshared = 0 .
value: is an initial value to set the semaphore to
Example of use:    sem_init(&sem_name, 0, 4);

To wait on a semaphore, use sem_wait:
            int sem_wait(sem_t *sem);
Example of use:              sem_wait(&sem_name);

          If the value of the semaphore is negative, the calling process blocks; one of the
           blocked processes wakes up when another process calls sem_post.


Another way to wait on semaphore :
   int sem_trywait(sem_t *sem)
               A non-blocking variant of sem_wait
               If the sem has non-zero count, the count is automatically decreased and
                immediately returns 0.
               If the semaphore count is zero, it immediately returns with error EAGAIN.

To increment the value of a semaphore, use sem_post:
            int sem_post(sem_t *sem);
Example of use:              sem_post(&sem_name);

          It increments the value of the semaphore and wakes up a blocked process waiting
           on the semaphore, if any.
To find out the value of a semaphore, use
            int sem_getvalue(sem_t *sem, int *valp);
       gets the current value of sem and places it in the location
        pointed to by valp
Example of use:
        int value;
        sem_getvalue(&sem_name, &value);
        printf("The value of the semaphors is %d\n", value);

To destroy a semaphore, use
        int sem_destroy(sem_t *sem);
       destroys the semaphore; no threads should be waiting on the
        semaphore if its destruction is to succeed.
Example of use:
       sem_destroy(&sem_name);

Example: Thread synchronization using POSIX semaphore
#include<pthread.h>
#include <semaphore.h>

void *Do_Task(void *);
int val;         /* global for both threads to access */
sem_t sem;
int main()
 { pthread_t tidA, tidB;
   sem_init(&sem, 0, 1);
     pthread_create(&tidA, NULL, &Do_Task,NULL);
     pthread_create(&tidB,NULL,&Do_Task,NULL);
     pthread_join(tidA,NULL);
     printf(“Thread A terminated Value is:=%d\n”,val);
     pthread_join(tidB,NULL);
      printf(“Thread B terminated Value is :=%d\n”,val);
 sem_destroy(&sem);
exit(0);
 }
void *Do_Task (void *arg)
{ int i;
   for(i=0;i<10;i++)
    { printf("Waiting to enter critical region...\n");
      sem_wait(&sem);
            printf("Incrementing val\n", x);
     val=val+1;
            printf("New Value: %d\n", val);
         printf("Exiting critical region...\n");
    sem_post(&sem);
      }
printf(“Thread:%d Terminating….\n”,pthread_self());
 pthread_exit(0);
}
#include <pthread.h>     /* POSIX Threads */
#include <string.h>      /* String handling */
#include <semaphore.h>   /* Semaphore */

void handler ( void *ptr );
sem_t mutex;
int counter; /* shared variable */

int main()
{    int i,j;
    pthread_t thread_a;
    pthread_t thread_b;
    i = 0; /* argument to threads */
    j = 1;
  sem_init(&mutex, 0, 1); /* initialize mutex to 1 - binary semaphore
                           /* second param = 0 - semaphore is local */
   pthread_create (&thread_a, NULL, (void *) &handler, (void *) &i);
   pthread_create (&thread_b, NULL, (void *) &handler, (void *) &j);

    pthread_join(thread_a, NULL);
    pthread_join(thread_b, NULL);
    sem_destroy(&mutex); /* destroy semaphore */

   exit(0);
}
void handler ( void *ptr )
{   int x;
    x = *((int *) ptr);
    printf("Thread %d: Waiting to enter critical region...\n", x);
    sem_wait(&mutex);       /* decrement semaphore */
    /* START CRITICAL REGION */
    printf("Thread %d: Now in critical region...\n", x);
    printf("Thread %d: Counter Value: %d\n", x, counter);
    printf("Thread %d: Incrementing Counter...\n", x);
    counter++;
    printf("Thread %d: New Counter Value: %d\n", x, counter);
    printf("Thread %d: Exiting critical region...\n", x);
    /* END CRITICAL REGION */
    sem_post(&mutex);       /* increment semaphore */
    pthread_exit(0); /* exit thread */
}