Problems with conditions
Ger Hobbelt
ger@hobbelt.com
Tue Mar 30 07:15:34 GMT 2021
See
https://stackoverflow.com/questions/16522858/understanding-of-pthread-cond-wait-and-pthread-cond-signal/16524148,
also read ALL comments there as some details get explained further.
Compare your mutex lock.. Unlock code with the sample code in the answer
there: your code has "nothing to do that requires..." so do not need to
wait.
On Mon, Mar 29, 2021, 14:20 Markus Forrer via Pthreads-win32 <
pthreads-win32@sourceware.org> wrote:
> I have re-implemented the C++ class OSEvent for a Windows simulation that
> exists for a Linux platform. Thereby I have the problem that the function
> pthread_cond_wait() does not wait until pthread_cond_signal() is called.
> Something I have misunderstood.
>
> Many thanks for any hints!
>
>
> OSEvent::OSEvent()
> {
> pthread_condattr_init(&_conditionAttribute);
> pthread_cond_init(&_condition, &_conditionAttribute);
> pthread_mutexattr_init(&_mutexAttribute);
> pthread_mutexattr_settype(&_mutexAttribute, PTHREAD_MUTEX_ERRORCHECK);
> pthread_mutex_init(&_mutex, &_mutexAttribute);
> }
>
> OSEvent::~OSEvent()
> {
> pthread_cond_destroy(&_condition);
> pthread_condattr_destroy(&_conditionAttribute);
> pthread_mutex_destroy(&_mutex);
> pthread_mutexattr_destroy(&_mutexAttribute);
> }
>
> void OSEvent::signal()
> {
> pthread_mutex_lock(&_mutex);
> pthread_cond_signal(&_condition);
> pthread_mutex_unlock(&_mutex);
> }
>
> OSEventError OSEvent::timedwait(uint32_t timeout)
> {
> struct timespec timeoutTime;
> timeoutTime.tv_sec = timeout / 1000;
> timeoutTime.tv_nsec = 1000000 * (timeout % 1000);
> OSEventError success = OSEventError::NoError;
> pthread_mutex_lock(&_mutex);
>
> // Timeout forever
> if (timeout == 0)
> {
> if (pthread_cond_wait(&_condition, &_mutex) != 0)
> {
> success = OSEventError::Timeout;
> }
> }
>
> // Timeout time
> else
> {
> if (pthread_cond_timedwait(&_condition, &_mutex, &timeoutTime) !=
> 0)
> {
> success = OSEventError::Timeout;
> }
> }
>
> pthread_mutex_unlock(&_mutex);
> return success;
> }
>
>
More information about the Pthreads-win32
mailing list