Posted to tcl by aku at Wed Mar 27 20:17:03 GMT 2019view pretty

#!/bin/bash
# ######################################################################
## Synchronization functions (Barrier waiting for a number of subprocesses)
#
## Example of Usage
#
##	barrier start foo
##	( ... ; barrier pass foo P1 ) &   ;# spawn sub-process 1
##	( ... ; barrier pass foo P2 ) &   ;# spawn sub-process 2
##	 ...
##	( ... ; barrier pass foo Pn ) &   ;# spawn sub-process n
##	barrier wait foo P1 P2 ... Pn     ;# waits until all of P1 ... Pn have passed.
#

function barrier_start () {
    code="$1"
    rm -f ${code}.*
}

function barrier_pass () {
    code="$1"
    process="$2"
    touch ${code}.${process}
}

function barrier_wait () {
    code="$1"
    shift
    processes="$@"
    while true
    do
      #debug
      #echo ___________/
      #ls ${code}.* 2> /dev/null

      ok=1
      for p in $processes
      do
	if test ! -f ${code}.${p}
	then
	    ok=0
	fi
      done
      if test $ok -eq 1 ; then break ; fi
      # Not everything has passed yet. Wait more
      sleep 1
    done
    rm ${code}.*
}

cmd="$1";shift
case $cmd in
start) barrier_start "$@" ;;
wait)  barrier_wait  "$@" ;;
pass)  barrier_pass  "$@" ;;
*)     echo 1>2 "Unknown command $cmd, expected on of start, pass, or wait" ;;
esac