How does deadlocks and livelocks behave in multithreaded code?

In multithreaded programming, deadlocks and livelocks are two important issues that can arise, leading to inefficient resource utilization and potential application crashes.

Deadlocks

A deadlock occurs when two or more threads are unable to proceed because each is waiting for the other to release a resource. In a deadlock situation, threads are blocked permanently until the system is reset or resources are released by an external force. This situation arises frequently in scenarios where multiple locks are being held.

Livelocks

A livelock, on the other hand, occurs when threads are not blocked but still cannot make progress. This happens when threads continually change their state in response to each other, without making any progress towards completing their task. In a livelock situation, the threads are actively changing states, but they are unable to move forward.

Example


// Example of Deadlock in PHP
class Resource {
    public static $resourceA;
    public static $resourceB;
}

function thread1() {
    // Lock resource A
    lock(Resource::$resourceA);
    sleep(1); // Simulate work
    // Try to lock resource B
    lock(Resource::$resourceB);
}

function thread2() {
    // Lock resource B
    lock(Resource::$resourceB);
    sleep(1); // Simulate work
    // Try to lock resource A
    lock(Resource::$resourceA);
}

// Example of Livelock in PHP
function livelockExample() {
    $flag1 = true; 
    $flag2 = true;

    while ($flag1 && $flag2) {
        // Thread tries to access the shared resource
        if (/* condition to access resource */) {
            // Simulate switching state
            $flag1 = false;
            $flag2 = true;
            echo "Thread 1 is giving up its turn.\n";
        } else if (/* condition by the other thread */) {
            $flag1 = true;
            $flag2 = false;
            echo "Thread 2 is giving up its turn.\n";
        }
    }
}
    

multithreading deadlock livelock concurrency issues resource management