Can deadlock occur in process with multiple threads?

1 answer

Answer

1290006

2026-07-20 10:50

+ Follow

Yes. Whenever a thread needs to read or write to memory shared with concurrent threads, it must prevent other threads from writing to that memory at the same time. That is, the threads need to be synchronised. Typically, a thread will acquire a lock on that memory, releasing it when it has finished with the memory. Only one thread can acquire a lock at any given time, so if the lock is already acquired by another thread, the current thread must wait for it to be released.

However, there are often times where two or more locks need to be acquired. So long as every thread acquires locks in the exact same order this is not a problem. But if a thread acquires the locks in a different order, we can easily end up with a deadlock.

Consider the following pseudocode:

function f ()

{

acquire lock A

acquire lock B

// ...

release lock B

release lock A

}

function g ()

{

acquire lock B

acquire lock A

// ...

release lock A

release lock B

}

If f is invoked in one thread and g in another, we can easily end up with f acquiring lock A while g acquires lock B. Function f is then left in limbo waiting for function g to release lock B while g is waiting for f to release lock A. They are deadlocked because neither can progress any further.

ReportLike(0ShareFavorite

Copyright © 2026 eLLeNow.com All Rights Reserved.