Gerard-Meier

PHP fictional mutex

Apr 19th, 2012
30
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.81 KB | None | 0 0
  1. <?php
  2. /**
  3.   * While this is not a 100% proof solution for critical sections
  4.   * it does demonstrate how a mutex could work.
  5.   *
  6.   */
  7.  
  8.  
  9. $foo    = 0;
  10. $locked = false; // This is our mutex (mutual exclusion) lock.
  11.  
  12. function a() {
  13. global $foo;
  14. global $locked;
  15.    
  16.     // Wait till the other thread finishes (blocking!):
  17.     while($locked) { /* Do nothing (we call this busy-waiting) */ }
  18.  
  19.     $locked = true; // This will trigger the while loop for the other thread.
  20.     $foo    = $foo + 2;
  21.     $locked = false;
  22. }
  23.  
  24. function b() {
  25. global $foo;
  26. global $locked;
  27.    
  28.     // Wait till the other thread finishes (blocking!):
  29.     while($locked) { /* Do nothing (we call this busy-waiting) */ }
  30.  
  31.     $locked = true; // This will trigger the while loop for the other thread.
  32.     $foo    = $foo + 2;
  33.     $locked = false;
  34. }
  35.  
  36. print $foo;
  37. ?>
Advertisement
Add Comment
Please, Sign In to add comment