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++;
        }
}
/*
   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


No comments:

Post a Comment