I am creating a program which uses multiple threads, but I am not able to synchronize such that a function threaded by an thread1 always execute first and no another threads able to run change shared resources. I heard about mutex locks and semaphore but I have no idea how to use. my code still in progress so I am not able to shared it instead I want to understand changes in basic code which is pretty much similar.
also which one is better semaphore or mutex for this case.
also which one is better semaphore or mutex for this case.
C:
#include<pthread.h>
#include<stdio.h>
void *fun1();
void *fun2();
int shared=1;
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared);
}
void *fun1()
{
int x;
x=shared;
x++;
sleep(1);
shared=x;
}
void *fun2()
{
int y;
y=shared;
y--;
sleep(1);
shared=y;
}