<condition_variable> timed_wait, pthread_cond_timedwait requires pthread_condattr_setclock
Chris Fairles
chris.fairles@gmail.com
Tue Sep 9 14:36:00 GMT 2008
Ran into this issue testing timed_wait. Turns out pthreads needs to
set the clock something like so:
condition_variable::condition_variable()
{
#ifdef _GLIBCXX_USE_CLOCK_MONOTONIC
pthread_condattr_t __c_attr;
pthread_condattr_init(&__c_attr);
pthread_condattr_setclock(&__c_attr, CLOCK_MONOTONIC);
pthread_cond_init(&_M_cond, &__c_attr);
pthread_condattr_destroy(&__c_attr);
#elif defined(_GLIBCXX_USE_CLOCK_REALTIME)
pthread_condattr_t __c_attr;
pthread_condattr_init(&__c_attr);
pthread_condattr_setclock(&__c_attr, CLOCK_REALTIME);
pthread_cond_init(&_M_cond, &__c_attr);
pthread_condattr_destroy(&__c_attr);
#else
# ifdef __GTHREAD_COND_INIT
__gthread_cond_t __tmp = __GTHREAD_COND_INIT;
_M_cond = __tmp;
# else
int __e = __gthread_cond_init(&_M_cond, NULL);
if (__e)
__throw_system_error(__e);
# endif
#endif
}
Otherwise pthread_cont_timedwait won't work with CLOCK_MONOTONIC (the
setclock for CLOCK_REALTIME is just there for completeness but it
appears to be the default). Looks like clock_gettime returns time's
with different epochs when using the realtime vs. monotonic clock (on
my x64_64 linux box anyway).
The above certainly isn't a proposed solution but I'm wondering what
should be done here. We could extend gthread's to include the condattr
functions (init, setclock, destory) but I don't think they translate
well outside of pthreads. Also, __gthread_cond_init must be used
instead of the __GTHREAD_COND_INIT short-cut when using
CLOCK_MONOTONIC.
Chris
More information about the Libstdc++
mailing list