76 S = CreateSemaphore(0,initValue,SEM_VALUE_MAX,0);
78 _available = initValue;
79 pthread_mutex_init(&_waitMutex, NULL);
80 pthread_cond_init(&_cond, NULL);
89 pthread_cond_destroy(&_cond);
90 pthread_mutex_destroy(&_waitMutex);
103 bool acquire(
int n = 1,
int ms = 0)
const
106 while(n-- > 0 && rt==0)
108 rt = WaitForSingleObject((HANDLE)S, ms<=0?INFINITE:ms);
119 pthread_mutex_lock(&_waitMutex);
120 while (n > _available && rt == 0)
124 struct timespec timeToWait;
127 gettimeofday(&now,NULL);
129 timeToWait.tv_sec = now.tv_sec + ms/1000;
130 timeToWait.tv_nsec = (now.tv_usec+1000UL*(ms%1000))*1000UL;
132 rt = pthread_cond_timedwait(&_cond, &_waitMutex, &timeToWait);
136 rt = pthread_cond_wait(&_cond, &_waitMutex);
144 pthread_mutex_unlock(&_waitMutex);
161 if(WaitForSingleObject((HANDLE)S, 0) == WAIT_OBJECT_0)
174 pthread_mutex_lock(&_waitMutex);
177 pthread_mutex_unlock(&_waitMutex);
181 pthread_mutex_unlock(&_waitMutex);
197 if(ReleaseSemaphore((HANDLE)S, n, 0))
207 pthread_mutex_lock(&_waitMutex);
209 pthread_cond_broadcast(&_cond);
210 pthread_mutex_unlock(&_waitMutex);
226 return (
int)_count.load();
232 pthread_mutex_lock(&_waitMutex);
234 pthread_mutex_unlock(&_waitMutex);
245 void reset(
int init = 0 )
248 S = CreateSemaphore(0,init,SEM_VALUE_MAX,0);
258 mutable std::atomic<long> _count;
261 pthread_mutex_t _waitMutex;
262 pthread_cond_t _cond;