hukana pakaya
hukana pakaya

Reputation: 1

Locks with multiple threads parallel programming in C++

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

Answers (2)

Pete Becker
Pete Becker

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

quartzsaber
quartzsaber

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.

  1. If thread 1 starts first: Red, Blue, Green, Red, Blue, ...
  2. If thread 2 starts first: Blue, Green, Red, Blue, Green, ...
  3. If thread 3 starts first: Green, Red, Blue, Green, Red, ...

B) Yes, it can. And it probably will. Consider it:

  1. Thread 1 locks lock[0]
  2. Thread 2 locks lock[1]
  3. Thread 3 locks lock[2]
  4. Thread 1 try to lock lock[1], waiting for thread 2
  5. Thread 2 try to lock lock[2], waiting for thread 3
  6. Thread 3 try to lock lock[3], waiting for thread 1

Upvotes: 0

Related Questions