Question: typedef struct { pthread_mutex_t mutex; /* Add other variables */ } SmartLock; void init_lock (SmartLock* lock) { pthread_mutex_init(&(lock->mutex), NULL); } int lock (SmartLock* lock) {

typedef struct {

pthread_mutex_t mutex;

/* Add other variables */

} SmartLock;

void init_lock(SmartLock* lock) {

pthread_mutex_init(&(lock->mutex), NULL);

}

int lock(SmartLock* lock) {

pthread_mutex_lock(&(lock->mutex)); return 1;

}

void unlock(SmartLock* lock) {

pthread_mutex_unlock(&(lock->mutex)); }

void cleanup() { }

/* * Cleanup any dynamic allocated memory for SmartLock to avoid memory leak * You can assume that cleanup will always be the last function call * in main function of the test cases. */

As shown above, SmartLock will internally hold a pthread_mutex_t instance for correct locking and unlocking mechanism. You need to update init_lock(), lock(), unlock() and cleanup() functions to incorporate the deadlock prevention logic in SmartLock. While APIs for init_lock() and unlock() appear straightforward, the lock() function returns an int value. This value should either be 0or 1 where 1 indicates that the lock got acquired and 0 indicates that the lock was not acquired (in order to prevent deadlocks). This means, even if the program calls lock, it is not always guaranteed to acquire the lock and hence, it must first check the return value before proceeding, as shown below

while(lock(&mySmartLock) == 0);

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!