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

前端 未结 2 1209
梦如初夏
梦如初夏 2021-02-04 09:21

I\'m looking for something could be used for polling (like select, kqueue, epoll i.e. not busy polling) in C/C++. In oth

相关标签:
2条回答
  • 2021-02-04 09:44

    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.

    0 讨论(0)
  • 2021-02-04 09:49

    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
    
    0 讨论(0)
提交回复
热议问题