Reputation: 1
How to answer this? please help.
Consider the following program with 3 threads.
locks l1, l2, l3;
*Thread 1
while(1){
l1.lock();
l2.lock();
printf(“Red”);
l3.unlock();
l1.unlock();}
*Thread 2
while(1){
l2.lock();
l3.lock();
printf(“Green”);
l1.unlock();
l2.unlock();}
*Thread 3
while(1){
l3.lock();
l1.lock();
printf(“Blue”);
l2.unlock();
l3.unlock();}
a) What are the possible outcomes of the above program. Can you explain how this'll happen? b) Will this code lead to a deadlock?
Upvotes: 0
Views: 1258
Reputation: 76498
It depends on what l1.lock()
, l1.unlock()
, etc., actually do. Since this is tagged C++ (although the title says C), if these function calls are managing std::mutex
objects, the result is undefined behavior, with each thread unlocking a mutex that it didn't lock.
Upvotes: 1
Reputation: 174
For the sake of readibly, I'll refer to locks as an array (eg. lock[0], lock[1], lock[2]
)
A) Depends on which thread starts executing first.
B) Yes, it can. And it probably will. Consider it:
lock[0]
lock[1]
lock[2]
lock[1]
, waiting for thread 2lock[2]
, waiting for thread 3lock[3]
, waiting for thread 1Upvotes: 0