Porting windows manual-reset event to Linux?

后端 未结 7 1563
别那么骄傲
别那么骄傲 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 06:00

    No there isn't any easier solution but the following code will do the trick:

    void LinuxEvent::wait()
    {
        pthread_mutex_lock(&mutex);
    
        int signalValue = signalCounter;
    
        while (!signaled && signalValue == signalCounter)
        {
            pthread_cond_wait(&condition, &mutex);
        }
    
        pthread_mutex_unlock(&mutex);
    }
    
    void LinuxEvent::signal()
    {
        pthread_mutex_lock(&mutex);
    
        signaled = true;
        signalCounter++;
        pthread_cond_broadcast(&condition);
    
        pthread_mutex_unlock(&mutex);
    }
    
    void LinuxEvent::reset()
    {
        pthread_mutex_lock(&mutex);
        signaled = false;
        pthread_mutex_unlock(&mutex);
    }
    

    When calling signal(), the event goes in signaled state and all waiting thread will run. Then the event will stay in signaled state and all the thread calling wait() won't wait. A call to reset() will put the event back to non-signaled state.

    The signalCounter is there in case you do a quick signal/reset to wake up waiting threads.

    0 讨论(0)
提交回复
热议问题