Porting windows manual-reset event to Linux?

后端 未结 7 1607
别那么骄傲
别那么骄傲 2020-11-30 05:23

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?

7条回答
  •  鱼传尺愫
    2020-11-30 05:51

    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 
    #include 
    
    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.

提交回复
热议问题