Article Listing 1 Listing 2 Listing 3 Listing 4
Listing 5 Listing 6 Listing 7 Listing 8 Listing 9
Listing 10 Listing 11 Listing 12 Listing 13 Sidebar aug2004.tar

Listing 3 keep_trying

{
    # Keep "trying" the semaphore until a resource is obtained or until the
    # program times out.

    local FUNC_NAME=keep_trying
    ${TRACE:-trace $FUNC_NAME $@}

    local semaphore=$1
    integer num_resources=$2
    integer pid=$3
    integer remaining_tries=$4

    assert_semaphore $semaphore

    while ! P_semaphore $semaphore $num_resources $pid
    do
        sleep $SLEEP_SECONDS
        if (( $remaining_tries >= 0 ))
        then
            if (( $remaining_tries == 0 ))
            then
                total=$(($TIMEOUT_TRIES*$SLEEP_SECONDS))
${INFO:-info "PID $$ timed out after $TIMEOUT_TRIES tries and $total seconds."}
                return 1
            else
                remaining_tries=$(( $remaining_tries - 1 ))
            fi
        fi
    done
    return 0
}