N=2

function assegna(){
    echo $2 >> $1
}

function leggi(){
    tail -1 $1
}


echo "1">alternanza

TMP=$(mktemp semafori.sh.XXXXXX)
trap "rm -f $TMP* 2>/dev/null" 0
rm $TMP

function p(){
    local p
    for p in $(seq $(( $1 * 10 )) $(( $1 * 10 + 9 )) ); do
	while true; do
	    lockfile $TMP
	    if [ $(leggi alternanza) -eq $1 ]; then
		echo $p
		assegna alternanza "$(( ( $(leggi alternanza) % 2 )  + 1))"
		rm -f $TMP
		break
	    else
		rm -f $TMP
	    fi
	    sleep 0.01
        done
    done
}

p 1 & 
p 2 &

wait %1 %2