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?
I prefer the pipe approach, because often one doesn't need just an event to wait for, but multiple objects e.g. WaitForMultipleObjects(...)
. And with using pipes one could easily replace the windows WaitForMultipleObjects
call with poll(...)
, select
, pselect
, and epoll
.
There was a light-weight method for process synchronization called Futex
(Fast Userspace Locking system call). There was a function futex_fd
to get one or more file descriptors for futexes. This file descriptor, together with possibly many others representing real files, devices, sockets or the like could get passed to select
, poll
, or epoll
. Unfortunately it was removed from the kernel. So the pipes tricks remain the only facility to do this:
int pipefd[2];
char buf[256]; // 256 is arbitrary
int r = pipe2(pipefd, O_NONBLOCK);
void setEvent()
{
write(pipefd[1], &buf, 1);
}
void resetEvent() { while( read(pipefd[0], &buf, sizeof(buf)) > 0 ) {;} }
void waitForEvent(int timeoutMS)
{
struct pollfd fds[1];
fds[0].fd = pipefd[0];
fds[0].events = POLLRDNORM;
poll(fds, 1, timeoutMS);
}
// finalize:
close(pipefd[0]);
close(pipefd[1]);