This pseudocode run concurrently in multiple threads causes deadlock:
Resource res1 = pool.get();
...
Resource res2 = pool.get();
...
pool.release(res2);
pool.release(res1);
Is that an expected behavior? (I guess it is)
Deadlock doesn’t seem to happen if the size of pool is twice of the number of threads – is this statement correct?
Is there a “scientific” name for this kind of deadlock in computer science? Would appreciate some links.
Thanks
Suppose you have two threads and two resources.
Thread A executes
res1 = pool.get()and acquires one resource. Thread B executesres1 = pool.get()and acquires one resource. Now the pool is exhausted, so neither thread can finishres2 = pool.get().The problem goes away if you have one spare resource (i.e. at least
n+1resources fornthreads), since in that case one thread is guaranteed to get two resources, finish, and thus release enough resources for the other threads to use. Increasing the number of resources improves parallelism; with twice as many resources as threads, every thread can get resources without blocking and thus all threads can execute in parallel.AFAIK this is simply known as “deadlock” since it’s essentially a textbook example of the phenomena. Both tasks are now waiting on each other to release the necessary resource.