68 S = CreateSemaphore(0,initValue,SEM_VALUE_MAX,0);
70 _available = initValue;
71 pthread_mutex_init(&_waitMutex, NULL);
72 pthread_cond_init(&_cond, NULL);
81 pthread_cond_destroy(&_cond);
82 pthread_mutex_destroy(&_waitMutex);
95 bool acquire(
int n = 1,
int ms = 0)
const
98 while(n-- > 0 && rt==0)
100 rt = WaitForSingleObject((HANDLE)S, ms<=0?INFINITE:ms);
111 pthread_mutex_lock(&_waitMutex);
112 while (n > _available && rt == 0)
116 struct timespec timeToWait;
119 gettimeofday(&now,NULL);
121 timeToWait.tv_sec = now.tv_sec + ms/1000;
122 timeToWait.tv_nsec = (now.tv_usec+1000UL*(ms%1000))*1000UL;
124 rt = pthread_cond_timedwait(&_cond, &_waitMutex, &timeToWait);
128 rt = pthread_cond_wait(&_cond, &_waitMutex);
136 pthread_mutex_unlock(&_waitMutex);
153 if(WaitForSingleObject((HANDLE)S, 0) == WAIT_OBJECT_0)
166 pthread_mutex_lock(&_waitMutex);
169 pthread_mutex_unlock(&_waitMutex);
173 pthread_mutex_unlock(&_waitMutex);
189 if(ReleaseSemaphore((HANDLE)S, n, 0))
199 pthread_mutex_lock(&_waitMutex);
201 pthread_cond_broadcast(&_cond);
202 pthread_mutex_unlock(&_waitMutex);
218 return (
int)_count.load();
224 pthread_mutex_lock(&_waitMutex);
226 pthread_mutex_unlock(&_waitMutex);
237 void reset(
int init = 0 )
240 S = CreateSemaphore(0,init,SEM_VALUE_MAX,0);
250 mutable std::atomic<long> _count;
253 pthread_mutex_t _waitMutex;
254 pthread_cond_t _cond;