QUESTION: How do I run processes in parallel, so that the counter (in counter.txt) would vary in value (instead of just "0" and "1")? That is, how to not sequentially run inc.sh and dec.sh?
The shared counter (a single number starting as 0) is in a file counter.txt.
counter.sh is (supposed to be; this is my problem) running (sub)processes in parallel:
#!/bin/bash
#counter.sh
N=${1:-100}
start=0
# First create counter.txt file with 0 as a start.
touch counter.txt
echo $start > counter.txt
echo "Start value: $start"
USAGE="usage: bash $0 #N# [-s]"
if [ $# -gt 2 ]; then
echo "$USAGE"
exit 1
elif [ $# -eq 2 ]; then
synchronized=true
fi
# create 2*N (parallel) processes:
if [[ $synchronized ]]; then
echo "SYNchronized:"
# This for loop is the crux of the counter.sh script:
for (( i = 0; i < $N; i++ )); do
( # Aren't brackets ( and ) enough for parallelism?
bash inc.sh $i -s # switch name (-s) is arbitrary; enough to have 2 args
bash dec.sh $(($i+1)) -s
)
done
else
echo "A-SYNchronized:"
for (( i = 0; i < N; i++ )); do
(
bash inc.sh $i
bash dec.sh $(($i+1))
)
done
fi
final=$(cat counter.txt)
echo "Final value: $final"
counter.sh calls this tiny script dec.sh (inc.sh differs only in plus "+", instead of "-"):
#!/bin/bash
#dec.sh (inc.sh has a plus (+)instead of minus)
if [ $# -eq 2 ]; then
lockfile -1 dec.lock
fi
number=$(cat counter.txt)
echo -n "Dec $1: $number -> "
number=$(($number - 1)) # minus is plus (+) in inc.sh
echo $number > counter.txt
echo "$number"
if [ $# -eq 2 ]; then
rm -f dec.lock
fi
The output of counter.sh is completely deterministic:
courteous@courteous-P5K ~/Documents/test $ bash counter.sh 5 -s
Start value: 0
SYNchronized:
Inc 0: 0 -> 1
Dec 1: 1 -> 0
Inc 1: 0 -> 1
Dec 2: 1 -> 0
Inc 2: 0 -> 1
Dec 3: 1 -> 0
Inc 3: 0 -> 1
Dec 4: 1 -> 0
Inc 4: 0 -> 1
Dec 5: 1 -> 0
Final value: 0
QUESTION: How do I run processes in parallel, so that the counter (in counter.txt) would vary in value (instead of just "0" and "1")? That is, how to not sequentially run inc.sh and dec.sh?