Skip to content

Instantly share code, notes, and snippets.

@cjbrigato
Created January 1, 2023 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjbrigato/9593e93b12058d0440f12e7fab8d612f to your computer and use it in GitHub Desktop.
Save cjbrigato/9593e93b12058d0440f12e7fab8d612f to your computer and use it in GitHub Desktop.
bash_multiprocess_with_complex_dependancies
#!/bin/bash
set -e
. <(base64 -d <<< X19fX19fXygpeyA6OyB9O18oKXsgOjsgfQ==)
_______ PREFLIGH UTILS _______________________________________________________________
NOW="$(date +%s)"
: ${STATES_DIR:=/tmp/spawn_states_$NOW}
mkdir -p "$STATES_DIR"
trap "rm -rf $STATES_DIR" EXIT
: ${DEBUG:="yep"}
debugp() { [[ $DEBUG == "yep" ]] && printf '[DBG:PID<%s>] %s\n' "$!" "$1"; }
_______ MAGIC _______________________________________________________________
# spawn_with_dependencies func <comma_separated_prereq_func> &
spawn_with_dependencies () {
local _operation="$1"
debugp "Spawned func $1 with $2 as dependancies"
[[ -f "$STATES_DIR/$_operation" ]] && return 0
[[ "$2" != "" ]] && {
local _dependencies="$(sed 's/,/ /g' <<< "$2")"
while :;do
sleep 1
for dependency in $_dependencies; do [[ ! -f "$STATES_DIR/$dependency" ]] && continue 2; done
break
done ; }
$_operation
touch $STATES_DIR/$_operation
}
_______ PROGAM _______________________________________________________________
a () { echo "a: i will sleep 2sec and have no dependancies"; sleep 2; }
b () { echo "b: i will sleep 5sec and depends on a and c"; sleep 5; }
c () { echo "c: i will sleep 1sec and depends on a"; sleep 1; }
d () { echo "d: i just echo lol and depends on a,b and c"; echo " -> lol"; }
e () { echo "e: b,c and d were done before me" ; }
main () {
spawn_with_dependencies e b,c,d &
spawn_with_dependencies a &
spawn_with_dependencies b a,c &
spawn_with_dependencies c a &
spawn_with_dependencies d a,b,c &
wait -f
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment