mutex.h
上传用户:psq1974
上传日期:2007-01-06
资源大小:1195k
文件大小:1k
源码类别:

mpeg/mp3

开发平台:

C/C++

  1. /* Copyright (C) 1998, 1999 State University of New York at Stony Brook
  2.    Author: Andrew V. Shuvalov ( andrew@ecsl.cs.sunysb.edu )
  3.    Software license is located in file "COPYING"
  4. */
  5. #ifndef _mutex_h_
  6. #define _mutex_h_
  7. #include "exceptions.h"
  8. /** defines the abstract Unix/Windoze interface to mutexes through two classes:
  9.     one to create the mutex, another to lock it.
  10.  */
  11. class mutex
  12. {
  13. # ifdef WIN32
  14.   /** to use in any log/error output */
  15.   std::string name;
  16.   HANDLE win_mutex_h;
  17. # endif  
  18. public:
  19.   mutex( const char *_name ) : name( _name )
  20.     {
  21. #     ifdef WIN32
  22.       win_mutex_h = CreateMutex( NULL, FALSE, NULL );
  23. #     endif  
  24.     }
  25.   ~mutex() 
  26.     {
  27.       // in Windows - nothing to do (?)
  28.     }
  29.   void wait( int seconds )
  30.     {
  31. #     ifdef WIN32
  32.       DWORD err = WaitForSingleObject( win_mutex_h, seconds * 1000 );
  33.       if( err == WAIT_FAILED )
  34. throw MutexErrorException( "mutex %s error: %s", name.c_str(), 
  35.    sys_errlist[errno] );
  36.       if( err == WAIT_TIMEOUT )
  37. throw MutexTimeoutException( "mutex %s timeout", name.c_str() );
  38. #     endif  
  39.     }
  40.   void release()
  41.     {
  42. #     ifdef WIN32
  43.       ReleaseMutex( win_mutex_h );
  44. #     endif  
  45.     }
  46. };
  47. class wait_for_mutex
  48. {
  49.   mutex &mut;
  50. public:
  51.   wait_for_mutex( mutex &_mutex, int seconds ) : mut( _mutex )
  52.     {
  53.       _mutex.wait( seconds );
  54.     }
  55.   ~wait_for_mutex()
  56.     {
  57.       mut.release();
  58.     }
  59. };
  60. #endif  //  _mutex_h_