Program With Mutex:
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
// binary semaphore
pthread_mutex_t mutex;
int mails = 0;
void *counter()
{
// The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock().
// If the mutex is already locked, the calling thread shall block until the mutex becomes available.
// This operation shall return with the mutex object referenced by mutex in the locked state with the
// calling thread as its owner.
// If successful, the pthread_mutex_lock() and pthread_mutex_unlock() functions shall return zero;
// otherwise, an error number shall be returned to indicate the error.
for(int i=0;i<100000;i++)
{
// int pthread_mutex_lock(pthread_mutex_t *mutex);
pthread_mutex_lock(&mutex);
mails++;
// int pthread_mutex_unlock(pthread_mutex_t *mutex);
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,&counter,NULL);
pthread_create(&t2,NULL,&counter,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
printf("\n\n Count: %d",mails);
return 0;
}
Output:
Program Without Mutex: Inconsistent Output
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
pthread_mutex_t mutex;
int mails = 0;
void *counter()
{
for(int i=0;i<100000;i++)
{
mails++;
}
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,&counter,NULL);
pthread_create(&t2,NULL,&counter,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
// Expected Output: 200000 but output is inconsistent
printf("\n\n Count: %d",mails);
return 0;
}
Output:

