将Windows手动重置事件移植到Linux吗? [英] Porting windows manual-reset event to Linux?
问题描述
将Windows手动重置事件移植到pthread是否有更简单的解决方案, 比一个pthread条件变量+ pthread互斥锁+一个标志(如果设置或未设置事件)?
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?
推荐答案
Pthread是低级构造.不,没有更简单的机制. pthread_cond__*
在概念上类似于自动重置事件.请注意,pthread_cond_wait
可能会有虚假的唤醒,因此无论情况如何,都不要在没有某种外部标志的情况下使用它.
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);
}
这可能不适合您的用法,因为您通常会想使用其他锁来代替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.
这篇关于将Windows手动重置事件移植到Linux吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!