How do you use deadlocks and livelocks with a simple code example?

Deadlocks and livelocks are two types of concurrency issues that can arise in multithreaded programming. A deadlock occurs when two or more threads are waiting indefinitely for each other to release resources, while a livelock occurs when threads are actively changing states in response to each other, but still unable to proceed.

Deadlock Example

In this example, two threads are trying to acquire two locks, which causes a deadlock:

<?php function thread1() { lockA(); sleep(1); // Simulate some operation lockB(); } function thread2() { lockB(); sleep(1); // Simulate some operation lockA(); } // Simulating thread execution thread1(); thread2(); ?>

Livelock Example

In this example, two threads are trying to avoid a deadlock, but they continually yield to each other, which causes a livelock:

<?php $thread1 = true; $thread2 = true; while ($thread1 || $thread2) { if ($thread1) { echo "Thread 1 is yielding...\n"; $thread1 = false; // Yield $thread2 = true; // Allow Thread 2 to run } if ($thread2) { echo "Thread 2 is yielding...\n"; $thread2 = false; // Yield $thread1 = true; // Allow Thread 1 to run } } ?>

deadlock livelock concurrency multithreading PHP thread management