mutex.h
上传用户:psq1974
上传日期:2007-01-06
资源大小:1195k
文件大小:1k
- /* Copyright (C) 1998, 1999 State University of New York at Stony Brook
- Author: Andrew V. Shuvalov ( andrew@ecsl.cs.sunysb.edu )
- Software license is located in file "COPYING"
- */
- #ifndef _mutex_h_
- #define _mutex_h_
- #include "exceptions.h"
- /** defines the abstract Unix/Windoze interface to mutexes through two classes:
- one to create the mutex, another to lock it.
- */
- class mutex
- {
- # ifdef WIN32
- /** to use in any log/error output */
- std::string name;
- HANDLE win_mutex_h;
- # endif
- public:
- mutex( const char *_name ) : name( _name )
- {
- # ifdef WIN32
- win_mutex_h = CreateMutex( NULL, FALSE, NULL );
- # endif
- }
- ~mutex()
- {
- // in Windows - nothing to do (?)
- }
- void wait( int seconds )
- {
- # ifdef WIN32
- DWORD err = WaitForSingleObject( win_mutex_h, seconds * 1000 );
- if( err == WAIT_FAILED )
- throw MutexErrorException( "mutex %s error: %s", name.c_str(),
- sys_errlist[errno] );
- if( err == WAIT_TIMEOUT )
- throw MutexTimeoutException( "mutex %s timeout", name.c_str() );
- # endif
- }
- void release()
- {
- # ifdef WIN32
- ReleaseMutex( win_mutex_h );
- # endif
- }
- };
- class wait_for_mutex
- {
- mutex &mut;
- public:
- wait_for_mutex( mutex &_mutex, int seconds ) : mut( _mutex )
- {
- _mutex.wait( seconds );
- }
- ~wait_for_mutex()
- {
- mut.release();
- }
- };
- #endif // _mutex_h_