Listing 2 mutex class implementation

#include "mutex.h"
const int ERROR_DUPLICATE_NAME = 285;

#include <string.h>
#include <stdio.h>

mutex::mutex( const char const* name ) {

   // -----------------------------------------------------------
   // the first order of business is to create the name of the
   // semaphore. to do this, we will need 7 bytes (for "\\sem32\\")
   // plus enough for the name plus one more for the null.
   // ---------------------------------------------------------------

   sem_name = new char [ 8 + strlen( name ) ];

   // ---------------------------------------------------------------
   // now that the memory is allocated, copy "\\sem32\\" and the
   // semaphore name into the new string.
   // ---------------------------------------------------------------

   strcpy( sem_name, "\\SEM32\\" ); // create first part of string
   strcat( sem_name, name );        // append the user semaphore name

   handle = 0;
   rc = DosCreateMutexSem(          // create the semaphore
     sem_name,                     // name of semaphore
     &handle,                      // handle of semaphore
     0,                            // unused by OS/2
     0 );                          // initial state is owned

   if ( rc == ERROR_DUPLICATE_NAME ) {

      // ------------------------------------------------------
      // at some point, this semaphore has already been created
      // so we open it for use here
      // ------------------------------------------------------

      handle = 0;
      DosOpenMutexSem( sem_name, &handle );
   }

   // --------------------------------------------------------------
   // request the semaphore to block other threads from the resource
   // --------------------------------------------------------------

   DosRequestMutexSem( handle, SEM_INDEFINITE_WAIT );
   
   // -------------------------------------------------------------
   // by the time the code reaches here, we either waited for total
   // control, or we created the semaphore.
   // -------------------------------------------------------------

   return;
}

mutex::~mutex() {

   // ---------------------------------------------------------------
   // the function that created *this has ended, so we can release
   // the mutex semaphore
   // ---------------------------------------------------------------

   DosReleaseMutexSem( handle );
   delete [] sem_name;                    // free memory allocated
}
//End of File