#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
void func();
int a;
int main()
{
pthread_t thread1;
sem_t semaphore1;
sem_init(&semaphore1,0,1);
pthread_create(&thread1,NULL,(void *)func,NULL);
sem_wait (&semaphore1);
a=62;
printf("%d",a); \\ as i found on google
sleep(2); \\ i believe a value should be sticked to 62
sleep(1); \\ but output shows different why?
printf("%d",a);
sem_post(&semaphore1);
}
void func()
{
a=45;
sleep(1);
a=32;
a=75;
printf("hello");
}
When i Googled it.I found sem_wait locks the global variable so that no other thread access the variable.
But when i tried these code the output is
62
hello
75.
The a value got changed but note that the printf(“%d”,a) is under the sem_wait ,Whats wrong with my code?
Semaphores offer only advisory locking. They don’t know about variables and such, they lock regions of your code. They don’t enforce anything so you must call
waitandpostyourself.Here is what
waitand post really mean when used in your example.The way I see it,
mainasks for permission before entering.funcdoesn’t ask for permission before modifyinga.So
funcshouldwaitandpost.Of course, for this
sempahore1should be globally accessible.