Hi guys,
I hope everybody is doing fine. I have written this small program which solves the critical region problem. Only on of the two threads can make changes to a common variable called counter. I am using two semaphores, is it possible to write the same program using only one semaphore? Here have a look at my code
$ cat practise.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/sem.h>
int count = 0;
int pargc;
char **pargv;
sem_t sem1;
sem_t sem2;
void *thread1(void *);
void *thread2(void *);
int main(int argc, char *argv[])
{
pargc = argc;
pargv = argv;
if(argc != 3)
{
printf("Invalid no. of arguments!\n");
exit(-1);
}
else
{
sem_init(&sem1,count,1);
sem_init(&sem2,count,0);
pthread_t tid1;
pthread_t tid2;
int t1 = 1;
int t2 = 2;
pthread_attr_t attr1;
pthread_attr_t attr2;
pthread_attr_init(&attr1);
pthread_attr_init(&attr2);
{
pthread_create(&tid1,&attr1,thread1,(void *)t1);
pthread_create(&tid2,&attr2,thread2,(void *)t2);
}
{
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}
printf("\nThreads finished!\n");
}
return 0;
}
void *thread1(void *n)
{
int i = 0;
while(i < 3)
{
sem_wait(&sem1);
count++;
printf("Count = %d\n",count);
sem_post(&sem2);
i++;
}
pthread_exit(0);
}
void *thread2(void *n)
{
int i = 0;
while(i<3)
{
sem_wait(&sem2);
count--;
printf("Count = %d\n",count);
sem_post(&sem1);
i++;
}
pthread_exit(0);
}
And more thing, which semaphore am i using in this program, is it binary or counting semaphore???