views:

1655

answers:

2

is there any easier solution in porting a windows manual-reset event to pthread, than a pthread conditional-variable + pthread mutex + a flag if event is set or unset?

+2  A: 

Pthreads are low level constructs. No, there isn't a simpler mechanism; pthread_cond__* is conceptually similar to an auto-reset event. Be careful, pthread_cond_wait may have spurious wakeups, so it should never be used without some sort of external flag regardless of the situation.

Building your own wouldn't be too hard, though.

#include <pthread.h>
#include <stdbool.h>
struct mrevent {
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    bool triggered;
};
void mrevent_init(struct mrevent *ev) {
    pthread_mutex_init(&ev->mutex, 0);
    pthread_cond_init(&ev->cond, 0);
    ev->triggered = false;
}
void mrevent_trigger(struct mrevent *ev) {
    pthread_mutex_lock(&ev->mutex);
    ev->triggered = true;
    pthread_cond_signal(&ev->cond);
    pthread_mutex_unlock(&ev->mutex);
}
void mrevent_reset(struct mrevent *ev) {
    pthread_mutex_lock(&ev->mutex);
    ev->triggered = false;
    pthread_mutex_unlock(&ev->mutex);
}
void mrevent_wait(struct mrevent *ev) {
     pthread_mutex_lock(&ev->mutex);
     while (!ev->triggered)
         pthread_cond_wait(&ev->cond, &ev->mutex);
     pthread_mutex_unlock(&ev->mutex);
}

This may not fit your usage, as you will often have a different lock that you'd want to use in place of ev->mutex, but this is the gist of how it's typically used.

ephemient
Don't forget that the windows auto reset event will "remember" that it's been signalled and inform the next thread that waits and then reset itself. the pthread_cond_signal may actually do nothing if there are no threads waiting so the "event" in this case would appear to not have happened.
ScaryAardvark
+1  A: 

I think Windows Events are more akin to a semaphore. I.e. for auto-reset, you'd use a binary semaphore and the sem_timedwait() function.

Dhiraj Pallin