I have a doubt regarding synchronized threads
. See the below code
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<sys/types.h>
#include<semaphore.h>
int a=0;
sem_t s1, s2;
void* t1handler(void *data)
{
while(1){
sem_wait(&s1);
a++;
printf("incr %d\n",a);
sem_post(&s2);
}
}
void* t2handler(void* data)
{
while(1){
sem_wait(&s2);
a--;
printf("decr %d\n",a);
sem_post(&s1);
}
}
int main(){
pthread_t t1,t2;
sem_init(&s1,0,1);
sem_init(&s2,0,0);
pthread_create(&t1,NULL,t1handler,NULL);
pthread_create(&t2,NULL,t2handler,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
return 0;
}
May be not a good example, but here thread2
waits for thread1
to complete and vice versa to synchronize
. Here what is the use of threads
when both are not executing simultaneously?.
Any examples where threads
can be used for synchronization
?
Thanks in advance.