How would you use a mutex lock in the increment() and decrement() functions belo
ID: 3816877 • Letter: H
Question
How would you use a mutex lock in the increment() and decrement() functions below to ensure execution of the functions are thread-safe. Use the Posix Pthreads API and ignore error checking.
Note: The mutex lock to be used is already defined in __counter_t, and has been initialized in the init() function below.
The relevant Pthreads API functions are as follows:
Pthread_mutex_lock(Pthread_mutex_t *mutex);
Pthread_mutex_unlock(Pthread_mutex_t *mutex);
1 typedef struct __counter_t {
2 int value;
pthread_mutex_t lock;
3 } counter_t;
4
5 void init(counter_t *c) {
6 c->value = 0;
Pthread_mutex_init(&c->lock, NULL);
7 }
8
9 void increment(counter_t *c) {
10 c->value++;
11 }
12
13 void decrement(counter_t *c) {
14 c->value--;
15 }
16
Explanation / Answer
#include <bits/stdc++.h>
#include <thread> // std::thread
#include <mutex>
#include <pthread.h>
using namespace std;
typedef struct __counter_t
{
int value;
pthread_mutex_t lock;
} counter_t;
void init(counter_t *c)
{
c->value = 0;
pthread_mutex_init(&c->lock, NULL);
}
void increment(counter_t *c)
{
cout<<"increment count ";
pthread_mutex_trylock(&c->lock) ;
c->value++;
pthread_mutex_unlock(&c->lock) ;
cout<<"Count is "<<c->value<<endl;
}
void decrement(counter_t *c)
{
cout<<"decrement count ";
pthread_mutex_trylock(&c->lock) ;
c->value--;
pthread_mutex_unlock(&c->lock) ;
cout<<"Count is "<<c->value<<endl;
}
int main(int argc, char const *argv[])
{
counter_t obj;
init(&obj);
increment(&obj);
increment(&obj);
increment(&obj);
decrement(&obj);
cout<<"Final counter is "<<obj.value<<endl;
return 0;
}
=============================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ -std=c++11 mutex.cpp -lpthread
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
increment count
Count is 1
increment count
Count is 2
increment count
Count is 3
decrement count
Count is 2
Final counter is 2
=================================================================
Please rate my answer.Thank you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.