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

Suppose there are two threads T1 and T2, and each one executes the following fun

ID: 3639784 • Letter: S

Question

Suppose there are two threads T1 and T2, and each one executes the following function f()'s pseudo code. Suppose also that there is a special LOCK{} macro that protects access to the contained code, i.e. only one thread at a time can access the code contained within the LOCK. Is this f() function thread-safe? Explain why or why not. Is this function reentrant? Explain why or why not. For both questions, if it's not the case, explain how the code should be changed.

int var1 = 0; // global

void f(int *i){

LOCK{
*i = var1 + 3;
}

var1 = *i + 4;

}

Explanation / Answer

It is neither thread safe nor re-entrant. To be thread-safe, the write to var1 needs to move inside the LOCK. Imagine two processes concurrently call the function. P1 gets the lock, and P2 waits for it. P1 reads var1, and releases the lock. At this point, assume P1 loses control of the process and P2 runs to completion, reading and modifying var1. P1 the resumes and modifies var1 again with a different value. Functions with simple locks are inherently non-reentrant. This one fails because (a) it accesses a statically-linked variable, and (b) because if it is re-entered by the same thread the thread will suspend waiting for itself to release the lock. The LOCK macro needs to check whether the thread/process trying to obtain the lock already has it and then do something different (such as recursively granting the lock).

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote