Thread Synchronization

I have created a program for thread synchronization using thread and binary semaphore. The program prints ping pong in synchronized fashion. The code of the program is given below; The code is compiled in Linux using gcc.

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include <semaphore.h>

sem_t mutex1;
sem_t mutex2;
void * testThread1(void *parg);
void * testThread2(void *parg);
int main(void){
pthread_t thread1,thread2;
int rc1,rc2;

sem_init(&mutex1, 0, 1);
sem_init(&mutex2, 0, 1);

//sem_wait(&mutex1);
sem_wait(&mutex2);

rc1 = pthread_create(&thread1,NULL,testThread1,NULL);
//sem_wait(&mutex2);
rc2 = pthread_create(&thread2,NULL,testThread2,NULL);

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

return 0;

}

void * testThread1(void *parg){
int count = 0;
//sem_post(&mutex2);
while(count <5){
sem_wait(&mutex1);
printf(“Ping \n”);
count = count + 1;
//sem_post(&mutex2);
sem_post(&mutex2);
}
}

void * testThread2(void *parg){
int count = 0;
//sem_post(&mutex1);
while(count<5){
sem_wait(&mutex2);
printf(“Pong \n”);
count = count + 1;
//sem_post(&mutex1);
sem_post(&mutex1);
}
}

Leave a comment