196k views
1 vote
In the following code, use a lock to protect any data that might need protecting. Keep your critical sections as small as possible. (10%) int flag = 0; int a = 0; void thread_a(){ a += 2; Flag = 1; } 1 void thread_b(){ int b = 0; if (flag) { b++; } b += 3; a -= b; }

1 Answer

3 votes

Answer:

A mutex is used here.

A mutex is a locking mechanism set before using a shared resource and is released after using the shared resource. When the lock is set, only one task accesses the mutex.

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<pthread.h>

#include<unistd.h>

pthread_t tid[2];

int flag=0;

int a = 0;

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

void *thread_a(void *arg)

{

pthread_mutex_lock(&lock);

a += 2;

pthread_mutex_unlock(&lock);

flag = 1;

return NULL;

}

void *thread_b(void *arg)

{

int b = 0;

if(flag){

b++;

}

b += 3;

pthread_mutex_lock(&lock);

a -= b;

pthread_mutex_unlock(&lock);

return NULL;

}

int main()

{

while(1) {

pthread_create(&tid[0],NULL,thread_a,NULL);

pthread_create(&tid[1],NULL,thread_b,NULL);

sleep(1);

}

pthread_exit(NULL);

return 0;

}

User Jonthornham
by
5.9k points