📄 unixsemaphore.cpp
字号:
//// This file is part of the "More for C++" library//// Copyright (c) 1999-2003 by Thorsten Goertz (thorsten@morefor.org)//// The "More for C++" library is free software; you can redistribute it and/or// modify it under the terms of the license that comes with this package.//// Read "license.txt" for more details.//// THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES// OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.////////////////////////////////////////////////////////////////////////////////#include <errno.h>#include <sys/time.h>#include "unixsemaphore.hpp"using namespace more;using namespace more::os;using namespace more::os::unix_;////////////////////////////////////////////////////////////////////////////////static pthread_mutex_t mutexInitializer = { 0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, { 0, 0 } };static pthread_cond_t condInitializer = PTHREAD_COND_INITIALIZER;////////////////////////////////////////////////////////////////////////////////UnixSemaphore::UnixSemaphore( size_t nNoOfResources): m_mutex( mutexInitializer ), m_condition( condInitializer ){ m_nNoOfResources = nNoOfResources; m_nNoOfAcquiredResources = 0;}////////////////////////////////////////////////////////////////////////////////void UnixSemaphore::finalize( ){ pthread_cond_destroy( &m_condition ); pthread_mutex_destroy( &m_mutex );}////////////////////////////////////////////////////////////////////////////////void UnixSemaphore::acquire( size_t nMillisecondsToWait) throw( Semaphore::TimeOut ){ int nError = 0; pthread_mutex_lock( &m_mutex ); while( nError == 0 && m_nNoOfAcquiredResources == m_nNoOfResources ) { if( nMillisecondsToWait > 0 ) { timeval now; timespec then; size_t nSeconds = nMillisecondsToWait / 1000; size_t nNanoseconds = 1000000 * ( nMillisecondsToWait % 1000 ); gettimeofday( &now, 0 ); then.tv_sec = now.tv_sec + nSeconds; then.tv_nsec = 1000 * now.tv_usec + nNanoseconds; nError = pthread_cond_timedwait( &m_condition, &m_mutex, &then ); } else { nError = pthread_cond_wait( &m_condition, &m_mutex ); } } if( nError == 0 ) { m_nNoOfAcquiredResources++; } pthread_mutex_unlock( &m_mutex ); if( nError == ETIMEDOUT ) { throw Semaphore::TimeOut( ); }}////////////////////////////////////////////////////////////////////////////////void UnixSemaphore::acquire( ){ acquire( 0 );}////////////////////////////////////////////////////////////////////////////////void UnixSemaphore::release( ){ pthread_mutex_lock( &m_mutex ); m_nNoOfAcquiredResources--; pthread_cond_signal( &m_condition ); pthread_mutex_unlock( &m_mutex );}////////////////////////////////////////////////////////////////////////////////
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -