Simple Distributed Mutual Exclusion Algorithm for two processes communicating with message passing.  This is a token based algorithm.

 

boolean   inCritical = false;          // true when process is in critical section

boolean   haveToken = true or false;   // true when this process holds the token

boolean   otherWaiting = false;        // true when the other process wants token

semaphore Iwant = 0;                   // lock to wait until I get the token

semaphore Uwant = 0;                   // lock to wait until other can get token

 

// The local process gains access to the critical section by calling wantME

void wantME( ) {

     if ( !haveToken ) {               // if this process does not have the token

          send request;                // ask other process for the token

          p( Iwant );                  // wait for token to arrive

     }

     inCritical = true;

}

 

// The local process calls this when it wants to release the critical section.

void releaseME( ) {

     inCritical = false;

     if ( otherWaiting )               // if the other process wants the token

          v( Uwant );                  // let listener send token

}

 

// This separate thread runs all the time waiting for messages from the other process.

listening thread

do forever {

     receive message;                  // receive token or request message

     if ( message is token ) {         // if we received the token

          haveToken = true;

          v( Iwant );                  // allow this process in critical section

     } else {                         // message is request for token

          if ( inCritical ) {          // if local process already in critical section

              otherWaiting = true;

              p( Uwant );             // wait until this process releases section

          }

          haveToken   = false;         // send token to other process

          otherWaiting = false;

          send token;

     }

}