Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any equivalents to the futex in Linux/Unix?

I'm looking for something could be used for polling (like select, kqueue, epoll i.e. not busy polling) in C/C++. In other word, I need to block a thread, and then wake it up in another thread with as little overhead as possible.

A mutex + condition variable works, but there is a lot of overhead. A futex also works, but that's for Linux only (or maybe not?). Extra synchronization is not required as long as the polling itself works properly, e.g. no race when I call wait and wake in two threads.

Edit: If such a "facility" doesn't exist in FreeBSD, how to create one with C++11 built-in types and system calls?

Edit2: Since this question is migrated to SO, I'd like to make it more general (not for FreeBSD only)

like image 669
GuLearn Avatar asked Apr 24 '14 19:04

GuLearn


1 Answers

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:

  1. user-mode synchronisation of the count (with a CAS or similar)
  2. kernel management of the wait queue and thread sleep/wait

I assume the mutex + condvar overhead you're worried about is the cond_wait->re-lock->unlock sequence, which is indeed avoided here.

like image 78
Useless Avatar answered Sep 22 '22 16:09

Useless