windows - 将 Windows 手动重置事件移植到 Linux?

标签 windows linux multithreading pthreads

将 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/

相关文章:

windows - 我在将 wmic 的输出 append 到文本文件时遇到问题

php - File_get_contents 函数不适用于 Windows?

linux - Linux 上的多播

linux - 在 Go 中使用目录观察器时,等待文件复制完成

multithreading - 原子读取的用例是什么

c++ - 多线程 unordered_map

c++ - 当承载全局钩子(Hook)的可执行进程崩溃时,全局钩子(Hook)会发生什么情况?

windows - 忽略 vendor 目录

linux - 在 Linux 中读取文件中每一行的更好方法是什么?

java - 柜台忙碌等待