A deadlock is a situation wherein two or more competing actions are waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like ‘the chicken or the egg‘.

WikiPage : http://en.wikipedia.org/wiki/Deadlock

deadlock_test1.php

<?php
$fp1 = fopen("foo1.txt", "w");
if (flock($fp1, LOCK_EX)) {
print "Got lock for foo1.txt!n";
sleep(10);
 
$fp2 = fopen("foo2.txt", "w");
if (flock($fp2, LOCK_EX)) {
 
print "Got lock foo2.txt!n";
sleep(10);
 
}
flock($fp2, LOCK_UN);
 
flock($fp1, LOCK_UN);
}
?>

deadlock_test2.php

<?php
$fp1 = fopen("foo2.txt", "w");
if (flock($fp1, LOCK_EX)) {
print "Got lock foo2.txt!n";
sleep(10);
 
$fp2 = fopen("foo1.txt", "w");
if (flock($fp2, LOCK_EX)) {
 
print "Got lock foo1.txt!n";
sleep(10);
 
}
flock($fp2, LOCK_UN);
 
flock($fp1, LOCK_UN);
}
?>

Run deadlock_test1.php and deadlock_test2.php in 2 different shell at a same time to get dead lock. :)

  • Share/Bookmark

2 Responses to “Basic dead lock example”

  1. admin says:

    Nice .. so If a person wants to kill a server he gotta run this !!!

  2. J says:

    Modern production servers have advanced deadlock protection, so if you are looking to kill a production engine, tough luck.

    They do it by one of these

    1. Mutual exclusion Only one process can use a resource at
    a time
    2. Hold-and-wait A process continues to hold a resource
    while waiting for other resources
    3. No preemption No resource can forcibly be removed from
    a process holding it
    4. Circular Wait There is a circular chain of processes where
    each holds a resource that is needed by the next in the
    circle

    Still, its a good example as not many are designed for deadlock prevention !

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

© 2010 Think Lamp Suffusion WordPress theme by Sayontan Sinha