bash done 53 lines

master
Bel LaPointe 2022-04-13 07:16:26 -06:00
parent 4e75ec8771
commit a8edc611cd
1 changed files with 63 additions and 0 deletions

63
src/bash.sh Normal file
View File

@ -0,0 +1,63 @@
#! /bin/bash
main() {
set -e
set -o pipefail
cleanup() {
if jobs -p | grep -q .; then
kill -9 $(jobs -p) &> /dev/null
fi
}
trap cleanup EXIT
export _D="$(mktemp -d)"
export _P=3
export _N=100
for i in $(seq 0 $((_P-1))); do
mkfifo "$_D/pipe.$i"
done
scatter
gather
rm -rf "$_D"
}
scatter() {
for i in $(seq 0 $((_P-1))); do
_scatter $i &
done
}
_scatter() {
local i="$1"
local chunk=$((_N/_P))
local start=$((chunk*i))
if ((i==_P-1)); then
chunk=$((chunk+_N%_P))
fi
local result=0
for j in $(seq $start $((start+chunk))); do
((result+=j)) || true
done
echo "> _scatter $i processing $start..$((start+chunk)) found $result" >&2
echo $result > "$_D/pipe.$i"
}
gather() {
echo "> gather..." >&2
local ttl=0
for f in "$_D"/pipe.*; do
echo "> cat $f" >&2
ttl=$((ttl+$(timeout 1 cat "$f" || echo 0)))
done
echo "> wait" >&2
wait
echo "> /gather $ttl" >&2
}
if [ "$0" == "$BASH_SOURCE" ]; then
main "$@"
fi