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 4 P_semaphore

{
    # P_semaphore tries to grab a resource. The function effectively
    # decrements the count or value of the semaphore if one is obtained.
    # Returns 0 if a resource is obtained; otherwise, returns 1.

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

    local semaphore=$1
    integer num_resources=$2
    integer pid=$3
    integer semaphore_value=$(get_semaphore_value $semaphore)

    assert_semaphore $semaphore

    ${INFO:-info "Semaphore $semaphore has $num_resources resource(s)."}
    ${INFO:-info "Value of semaphore $semaphore is: $semaphore_value"}

    if (( $semaphore_value > 0 ))
    then
        ${INFO:-info "Trying to grab a resource from semaphore $semaphore ..."}
        integer resource_num=0
        while (( $resource_num < $num_resources ))
        do
            if grab_resource $semaphore $resource_num $pid
            then
                ${INFO:-info "PID $pid grabbed resource $resource_num."}
                return 0
            else
                ${INFO:-info "Resource $resource_num was in use."}
                resource_num=$(($resource_num+1))
            fi
        done
    else
        if (( $(time_since_last_wipe $semaphore) > $WIPE_INTERVAL ))
        then
            wipe_semaphore $semaphore
        fi
    fi
    ${INFO:-info "All resources for semaphore $semaphore were in use."}
    return 1
}