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:

*/

No comments:

Post a Comment