不幸的是,cygwin的GCC 4.5.3并行线程库实现不支持POSIX标准功能
int pthread_mutex_timedlock(pthread_mutex_t* mutex, struct timespec* abstime);
有没有人一个好主意,如何实现在一个互斥体包装类这种方法很好的解决方法? 可使用pthread_mutex_trylock()
与(毫秒为主) nanosleep()
调用? 我没有对后者的想法感觉不错,但不管怎么说,C ++实现看起来是这样的:
bool MyPosixMutexWrapper::try_lock(const TimeDuration<>& timeout)
{
if(valid)
{
if(timeout == TimeDuration<>::Zero)
{
if(pthread_mutex_trylock(&mutexHandle) == 0)
{
return true;
}
}
else
{
struct timespec now;
clock_gettime(CLOCK_REALTIME,&now);
TimeDuration<> tnow(now);
tnow += timeout;
struct timespec until = tnow.getNativeValue();
#if defined(_POSIX_TIMEOUTS)
if(pthread_mutex_timedlock(&mutexHandle,&until) == 0)
{
return true;
}
#else
long milliseconds = timeout.milliseconds();
while(milliseconds > 0)
{
if(pthread_mutex_trylock(&mutexHandle) == 0)
{
return true;
}
struct timespec interval;
struct timespec remaining;
interval.tv_sec = 0;
interval.tv_nsec = 1000000;
do
{
remaining.tv_sec = 0;
remaining.tv_nsec = 0;
if(nanosleep(&interval,&remaining) < 0)
{
if(errno == EINTR)
{
interval.tv_sec = remaining.tv_sec;
interval.tv_nsec = remaining.tv_nsec;
}
else
{
return false;
}
}
clock_gettime(CLOCK_REALTIME,&now);
tnow = TimeDuration<>(now);
if(tnow >= TimeDuration(until))
{
return pthread_mutex_trylock(&mutexHandle) == 0;
}
} while(remaining.tv_sec > 0 || remaining.tv_nsec > 0);
--milliseconds;
}
#endif
}
}
return pthread_mutex_trylock(&mutexHandle) == 0;
}
有没有人有这个代码一个更好的主意或改进措施?