[zeromq-dev] Improving latency using futexes?

Steven McCoy steven.mccoy at miru.hk
Tue Nov 24 18:40:20 CET 2009


Example usage of Futex,

void apc_futex_lock(volatile int* lock)
{
    int c;

    /*  Attempt to obtain a lock if not currently locked.  If the previous
     *  value was not 0 then we did not obtain the lock, and must wait.
     *  If the previous value was 1 (has no waiting processes) then we
     *  set the lock to 2 before blocking on the futex wait operation.
     *  This implementation suffers from the possible difficulty of
     *  efficently implementing the atomic xchg operation on some
     *  architectures, and could also cause unecessary wake operations by
     *  setting the lock to 2 when there are no additional waiters.
     */
    if((c = apc_cmpxchg(lock, 0, 1)) != 0) {
        if(c != 2) {
            c = apc_xchg(lock, 2);
        }
        while(c != 0) {
            apc_futex_wait(lock, 2);
            c = apc_xchg(lock, 2);
        }
    }

}

/* non-blocking lock returns 1 when the lock has been obtained, 0 if it
would bl
ock */
inline zend_bool apc_futex_nonblocking_lock(volatile int* lock)
{
    return apc_cmpxchg(lock, 0, 1) == 0;
}


inline void apc_futex_unlock(volatile int* lock)
{
    /* set the lock to 0, if it's previous values was not 1 (no waiters)
     * then perform a wake operation on one process letting it know the lock
     * is available.  This is an optimization to save wake calls if there
     * are no waiting processes for the lock
     */
    if(apc_xchg(lock,0) != 1) {
        apc_futex_wake(lock, 1);
    }
}

-- 
Steve-o
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.zeromq.org/pipermail/zeromq-dev/attachments/20091124/2f15ddfa/attachment.html>


More information about the zeromq-dev mailing list