home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / vc98 / crt / src / xlock.cpp < prev    next >
C/C++ Source or Header  |  1998-06-16  |  2KB  |  77 lines

  1. /***
  2. *xlock.cpp - thread lock class
  3. *
  4. *       Copyright (c) 1996, Microsoft Corporation. All rights reserved.
  5. *
  6. *Purpose:
  7. *       Define lock class used to make STD C++ Library thread-safe.
  8. *
  9. *Revision History:
  10. *       08-28-96  GJF   Module created, MGHMOM.
  11. *
  12. *******************************************************************************/
  13.  
  14. #ifdef  _MT
  15.  
  16. #include <xstddef>
  17. #include <windows.h>
  18. _STD_BEGIN
  19.  
  20. static CRITICAL_SECTION _CritSec;
  21.  
  22. static long _InitFlag = 0L;
  23.  
  24. static void _CleanUp()
  25. {
  26.         long InitFlagValue;
  27.  
  28.         if ( InitFlagValue = InterlockedExchange( &_InitFlag, 3L ) == 2L )
  29.             // Should be okay to delete critical section
  30.             DeleteCriticalSection( &_CritSec );
  31. }
  32.  
  33. _Lockit::_Lockit()
  34. {
  35.  
  36.         // Most common case - just enter the critical section
  37.  
  38.         if ( _InitFlag == 2L ) {
  39.             EnterCriticalSection( &_CritSec );
  40.             return;
  41.         }
  42.  
  43.         // Critical section either needs to be initialized.
  44.  
  45.         if ( _InitFlag == 0L ) {
  46.  
  47.             long InitFlagVal;
  48.  
  49.             if ( (InitFlagVal = InterlockedExchange( &_InitFlag, 1L )) == 0L ) {
  50.                 InitializeCriticalSection( &_CritSec );
  51.                 atexit( _CleanUp );
  52.                 _InitFlag = 2L;
  53.             }
  54.             else if ( InitFlagVal == 2L )
  55.                 _InitFlag = 2L;
  56.         }
  57.  
  58.         // If necessary, wait while another thread finishes initializing the
  59.         // critical section
  60.  
  61.         while ( _InitFlag == 1L )
  62.             Sleep( 1 );
  63.  
  64.         if ( _InitFlag == 2L )
  65.             EnterCriticalSection( &_CritSec );
  66. }
  67.  
  68. _Lockit::~_Lockit()
  69. {
  70.         if ( _InitFlag == 2L ) 
  71.             LeaveCriticalSection( &_CritSec );
  72. }
  73.  
  74. _STD_END
  75.  
  76. #endif
  77.