将 Windows 手动重置事件移植到 pthread 是否有更简单的解决方案, 比 pthread 条件变量 + pthread 互斥 + 事件设置或取消设置的标志?
最佳答案
Pthread 是低级结构。不,没有更简单的机制; pthread_cond__*
在概念上类似于自动重置事件。小心,pthread_cond_wait
可能有虚假唤醒,因此无论情况如何,都不应在没有某种外部标志的情况下使用它。
不过,构建您自己的并不难。
#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
,但这是通常使用方式的要点.
关于windows - 将 Windows 手动重置事件移植到 Linux?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/178114/