Semaphore implementation using POSIX Threads

Aim: To illustrate the semaphores in Linux using C for handling two threads.

Requirements:GCC Compiler with Linux OS

Explanation 

 This program has two threads, one for reading the input and another for converting the text to upper case letter. However, the thread for converting the text will wait for the semaphore to be released before it starts the operation.

Program:

 //illustration of semaphores.

#include <stdio.h>


#include <unistd.h>

#include <stdlib.h>

#include <string.h>

#include <ctype.h>

#include <pthread.h>

#include <semaphore.h>


#define BUFFER 1024

 


sem_t sem;

 

char buffer[BUFFER];


void *read_thread(void *arg)

 

{

while(strncmp("stop", buffer,4)!=0)

{

printf("Enter text");

fgets(buffer,BUFFER, stdin);

sem_post(&sem);

}

pthread_exit("read Thread exit successful");

}


void *convert_thread()

 

{

int i;

sem_wait(&sem);

while(strncmp("stop",buffer,4)!=0)

{

printf("Converted text");

for(i=0;i<strlen(buffer);i++)

printf("%c", toupper(buffer[i]));

sem_wait(&sem);

}

pthread_exit("convert_thread exit successfully");

}


int main()

 

{

int result;

pthread_t rthread, cthread;

void *thread_result;

result=sem_init(&sem,0,0);

if(result != 0)

{

printf("Semaphore initialisation failed");

exit(1);

}

printf("enter text, the program will convert it into upper caswe, to stop enter 'stop'\n");

result=pthread_create(&cthread, NULL, convert_thread, NULL);

if(result != 0)

{

printf("convert thread creation failed");

exit(1);

}


result=pthread_create(&rthread, NULL, read_thread, NULL);

 

if(result != 0)

{

printf("read Thread creation failed");

exit(1);

}


result=pthread_join(rthread, &thread_result);

 

if(result!=0)

{

printf("read Thread join failed");

exit(1);

}

printf("read threaed joined, %s \n", thread_result);


result=pthread_join(cthread, &thread_result);

 

if(result != 0)

{

printf("Convert thread join failed");

exit(1);

}


printf("Conmvert thread joined, %s \n", thread_result);

 

sem_destroy(&sem);

exit(0);


}

Observation:

In this program, one thread reads the input and another thread converts the input string into upper case letters. This is repeated till 'stop' typed. The prorgam can be compiled by


$ gcc -o multithread multithread.c -lpthread

 

Comments

Popular Posts