Porting windows manual-reset event to Linux?

后端 未结 7 1596
别那么骄傲
别那么骄傲 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:41

    You can easy implement manual-reset events with pipes:

    event is in triggered state -> there is something to read from the pipe

    SetEvent -> write()

    ResetEvent -> read()

    WaitForMultipleObjects -> poll() (or select()) for reading

    the "SetEvent" operation should write something (e.g. 1 byte of any value) just to put the pipe in non-empty state, so subsequent "Wait" operation, that is, poll() for data available for read will not block.

    The "ResetEvent" operation will read up the data written to make sure pipe is empty again. The read-end of the pipe should be made non-blocking so that trying to reset (read from) already reset event (empty pipe) wont block - fcntl(pipe_out, F_SETFL, O_NONBLOCK) Since there may be more than 1 SetEvents before the ResetEvent, you should code it so that it reads as many bytes as there are in the pipe:

    char buf[256]; // 256 is arbitrary
    while( read(pipe_out, buf, sizeof(buf)) == sizeof(buf));
    

    Note that waiting for the event does not read from the pipe and hence the "event" will remain in triggered state until the reset operation.

提交回复
热议问题