Skip to content

Instantly share code, notes, and snippets.

@naufalso
Created February 16, 2024 08:14
Show Gist options
  • Save naufalso/67e7e99b9a55e7ae92744fde04d0fcd7 to your computer and use it in GitHub Desktop.
Save naufalso/67e7e99b9a55e7ae92744fde04d0fcd7 to your computer and use it in GitHub Desktop.
Bash Script for Running Parallel Queue
#!/bin/bash
# initialize a semaphore with a given number of tokens
open_sem(){
mkfifo pipe-$$
exec 3<>pipe-$$
rm pipe-$$
local i=$1
for((;i>0;i--)); do
printf %s 000 >&3
done
}
# run the given command asynchronously and pop/push tokens
run_with_lock(){
local x
# this read waits until there is something to read
read -u 3 -n 3 x && ((0==x)) || exit $x
(
( "$@"; )
# push the return code of the command to the semaphore
printf '%.3d' $? >&3
)&
}
# Define the maximum of parallel process in the queue
N=4
open_sem $N
for i in {0..100}
do
run_with_lock [WRITE_YOUR_PROCESS_HERE]
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment