In: Computer Science
3. Add mutex locks to tprog2.c to achieve synchronization, and screenshot the output tprog2.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h>
void* print_i(void *ptr) {
printf("1: I am \n"); sleep(1); printf("in i\n");
}
void* print_j(void *ptr) {
printf("2: I am \n"); sleep(1); printf("in j\n");
}
int main() {
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, NULL); int rc2 = pthread_create(&t2, NULL, print_j, NULL);
exit(0);
}
Hope you like it and upvote me for the efforts
tprog3.c
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_mutex_t lock;
void* print_i(void *ptr)
{
pthread_mutex_lock(&lock);
printf("1: I am\n");
sleep(1);
printf("in i\n");
pthread_mutex_unlock(&lock);
}
void* print_j(void *ptr)
{
pthread_mutex_lock(&lock);
printf("2: I am\n");
sleep(1);
printf("in j\n");
pthread_mutex_unlock(&lock);
}
int main()
{
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, NULL);
int rc2 = pthread_create(&t2, NULL, print_j, NULL);
pthread_mutex_destroy(&lock);
exit(0);
}
Output
2: I am
in j
1: I am
in i
Summary: Without mutex,we can observe that, the print message "2: I am" is printed after just printing the message "1: I am". This is because while thread 1(print_i) is processing the scheduler has scheduled thread 2(print_j). And during execution of sleep(1) ie., which means thread 1 is sleeping for 1s, the thread 2 printed the message "2: I am" and it is followed by thread 1 message "in i" as thread 2 is executing sleep(1) during that time. Finally the message "in j" is printed
With mutex lock, thread 2 has locked using mutex and once the thread 2 finished printing all its messages it unlocks using mutex. This locking ensures that eventhough through context switching other threads that gets executed which is trying to lock the same lock(that is already locked by thread 2) will again go to sleep until the thread 2 unlocks it.