Alpha
Alpha
AlphaBeta: when quoting is solved

Digging Deeper

Concurrency

Introduction

Sometimes you need to run several slow tasks that don't depend on each other. Laravel's Concurrency facade runs them in child processes. So does Laravel Bash, which is the one time the two implementations agree.

Running Concurrent Tasks

count_posts()    { sleep 1; Post::count; }
count_comments() { sleep 1; Comment::count; }
fetch_weather()  { sleep 1; echo "Drizzle, 7°C"; }

mapfile -d '' -t results < <(
  Concurrency::run count_posts count_comments fetch_weather
)
echo "${results[2]}"   # Drizzle, 7°C

Three tasks that take a second each take one second in total. See it on the Dashboard.

How It Works

Concurrency::run() {
  local dir task pid i=0 j
  local -a pids=()
  dir=$(mktemp -d)
  for task in "$@"; do
    "$task" > "$dir/$i" &
    pids+=("$!")
    i=$((i + 1))
  done
  for pid in "${pids[@]}"; do
    wait "$pid" || { rm -rf "$dir"; return 1; }
  done
  for ((j = 0; j < i; j++)); do
    cat "$dir/$j"
    printf '\0'
  done
  rm -rf "$dir"
}
  1. & starts each task in a child process. $! is its PID.
  2. A child can't set its parent's variables, so each one writes to its own file in a private mktemp -d folder.
  3. wait "$pid" waits for each one and returns its exit code. A failed task is a thrown exception.
  4. The results come back in order, each followed by a NUL byte. mapfile -d '' splits on NUL.

Why NUL?

Results can contain newlines, tabs and spaces, but they can't contain a NUL byte, because Bash variables can't hold one. That makes it the only separator that's always safe. find -print0 | xargs -0 uses it for the same reason.

Why not xargs -P or parallel?

ToolWhy not
xargs -P 4It runs programs, not Bash functions, and the outputs come back interleaved in whatever order they finish.
GNU parallelExcellent, and written in Perl. We have a strict no-Perl policy, for now.
coprocBash only lets you have one coprocess at a time, and warns if you start a second.