Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

CS4315 Operating Systems Lab 3: Basic Synchronization using Mutex In this lab wo

ID: 3735838 • Letter: C

Question

CS4315 Operating Systems
Lab 3: Basic Synchronization using Mutex
In this lab work we will do some practice about basic synchronization.
Question 1 is about creating threads and each thread runs a different function.
Question 2 and 3 are about mutex lock (acquiring a lock and releasing a lock).
1. Run the following C program (tprog1.c) and observe the result on the screen.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// These two functions will run concurrently
void* print_i(void *ptr)
{
printf("I am in i ");
}
void* print_j(void *ptr)
{
printf("I am in j ");
}
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);
}

3. Add mutex locks to tprog2.c to achieve synchronization, and then observe the result on your
screen.

Explanation / Answer

Solution:

The mutex is added in the below code to achieve synchronization.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// These two functions will run concurrently
void* print_i(void *ptr)
{
printf("I am in i ");
}
void* print_j(void *ptr)
{
printf("I am in j ");
}
int main()
{

int mutex= 1; //This is our mutex variable which will be used in our code to achieve syncronization
pthread_t t1,t2;

if(mutex){

mutex--;
int rc1 = pthread_create(&t1, NULL, print_i, NULL);

mutex++;

}

if(mutex){

mutex--;

int rc2 = pthread_create(&t2, NULL, print_j, NULL);

mutex++;

}
exit(0);

mutex will be decremented (which means set to 0) when a process gets the access to the critical section in the code, and as soon as the process is back it will be set to one.

I hope this helps if you find any problem. Please comment below. Don't forget to give a thumbs up if you liked it. :)