Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to generate a deadlock with single lock

This is an interview question . In general the deadlock between 2 threads is generated when thread1 locks mutex1,and a moment before it tries to lock mutex2 ,thread 2 locks mutex2.After that tread 2 wants to lock mutex1.So they wait for each other forever.

The question was "Can you gave a scenario of deadlock with one mutex and any number of threads?"

like image 868
Yakov Avatar asked Dec 16 '22 04:12

Yakov


1 Answers

A deadlock requires 4 things:

Mutual Exclusion - refers to the idea of having a resource (a lock) that can be owned by a single thread.
No pre-emption - locks cannot be acquired forcefully
Circular Wait - refers to one thread waiting on another, that is waiting on itself (or a chain)
Hold and Wait - a thread is able to take one lock and wait for another

In an interview, it's usually more important to show them your thought processes and if you bring up these rules, they'll probably do more for you than trying to give a 'technically correct' trick answer.

You could do it this way, though:
Master thread locks a resource, then sends some tasks to the thread pool. These tasks wait for the resource. The master thread waits for the tasks.

like image 143
bdean20 Avatar answered Feb 01 '23 13:02

bdean20