John F. Dumas Vulcan Ware
_blank_

SLock


   SLock - A php class to allow safe access to shared resources
   by multiple threads of execution

    A classic example of where this would be useful would be
    a web counter where the current number of hits is stored in
    a text file.  So long as there is only one thread of
    execution, the sequence of events is:
   
       - read counter.txt (value is for example: 42)
       - add one to current value (value now: 43)
       - write new value to counter.txt
   
    With another thread of execution, the following can happen:
   
       - Thread 1 reads counter.txt (value is for example: 42)
       - Thread 2 reads counter.txt (also gets value: 42)
       - Thread 1 adds one to current value (value now: 43)
       - Thread 2 adds one to current value (value now: 43)
       - Thread 1 writes new value to counter.txt
       - Thread 2 writes new value to counter.txt
   
    The problem being that counter.txt *should* contain 44, not 43.
    By using SLock, these problems can be avoided - before
    reading the counter.txt file the script must acquire
    an SLock on a specified port and the lock is held until
    the file has been written.  Any other scripts would be
    denied the SLock until the first script finished.
   
    Here is a simple example, run two or more copies
    simultaneously to see the effect ...
    
       require('slock.inc');
   
       function basketBallPlayer()
       {
          print("\nI've got the ball!\n");
   
          for($i = 0; $i < 3; $i ++)
          {
             print("   I'm dribbling it ...\n");
             sleep(1);
          }
   
          print("Now I pass it to someone else ...\n");
       }
   
       for($i = 0; $i < 5; $i ++)
       {
          if(!SLock::doCall("basketBallPlayer", 8787, $errMsg))
             die($errMsg . "\n");
   
          sleep(2 + (rand() % 3));
       }
   

Notes

  • Since SLock calls: (socket_create, socket_bind, socket_close), php will need to have socket support. Frequently, this involves using '--enable-sockets' during the configuration of php prior to build.

Downloads


Return to Main Page