#!/bin/bash THREADS=5 TASKS=10 # execution function e() { echo "t:${1} (${SECONDS}s) - execute task ${2}" sleep 1 } # thread function t() { thread_id=${1} echo "t:${thread_id} (${SECONDS}s) started" a=0 while [[ ${a} -lt ${TASKS} ]]; do b=$(( ${a} % ${THREADS} )) if [[ ${b} = ${thread_id} ]]; then e ${thread_id} ${a} fi a=$(( ${a} + 1 )) done echo "t:${thread_id} (${SECONDS}s) done" } # run threads i=0 while [[ ${i} -lt ${THREADS} ]]; do t ${i} & i=$(( ${i} + 1 )) done # wait until all threads are done wait echo "done (${SECONDS}s)"
THREADS=5; TASKS=10 t:0 (0s) started t:0 (0s) - execute task 0 t:1 (0s) started t:1 (0s) - execute task 1 t:2 (0s) started t:2 (0s) - execute task 2 t:4 (0s) started t:4 (0s) - execute task 4 t:3 (0s) started t:3 (0s) - execute task 3 t:0 (1s) - execute task 5 t:1 (1s) - execute task 6 t:2 (1s) - execute task 7 t:4 (1s) - execute task 9 t:3 (1s) - execute task 8 t:0 (2s) done t:1 (2s) done t:2 (2s) done t:4 (2s) done t:3 (2s) done done (2s) THREADS=1; TASKS=5 t:0 (0s) started t:0 (0s) - execute task 0 t:0 (1s) - execute task 1 t:0 (2s) - execute task 2 t:0 (3s) - execute task 3 t:0 (4s) - execute task 4 t:0 (5s) done done (5s) THREADS=4; TASKS=2 t:1 (0s) started t:1 (0s) - execute task 1 t:2 (0s) started t:2 (0s) done t:3 (0s) started t:3 (0s) done t:0 (0s) started t:0 (0s) - execute task 0 t:1 (1s) done t:0 (1s) done done (1s)