I\'m looking for something could be used for polling (like select
, kqueue
, epoll
i.e. not busy polling) in C/C++. In oth
semaphores are not mutexes, and would work with slightly less overhead (avoiding the mutex+condvar re-lock, for example)
Note that since any solution where a thread sleeps until woken will involve a kernel syscall, it still isn't cheap. Assuming x86_64 glibc and the FreeBSD libc are both reasonable implementations, the unavoidable cost seems to be:
I assume the mutex + condvar overhead you're worried about is the cond_wait->re-lock->unlock sequence, which is indeed avoided here.
You want semaphores and not mutexes for the signaling between the to threads..
http://man7.org/linux/man-pages/man3/sem_wait.3.html
Semaphores can be used like a counter such as if you have a queue, you increment (post) to the semaphore every time you insert a message, and your receiver decrement (wait) on the semaphore for every message it takes out. If the counter reach zero the receiver will block until something is posted.
So a typical pattern is to combine a mutex and a semaphore like;
sender:
mutex.lock
insert message in shared queue
mutex.unlock
semaphore.post
receiver:
semaphore.wait
mutex.lock
dequeue message from shared structure
mutex.unlock