Last active
June 22, 2017 11:25
-
-
Save gpsarkar/cf55aa9a20c4d703dba15bd7160b1c09 to your computer and use it in GitHub Desktop.
Linux Tasks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Sample task | |
task(){ | |
sleep 0.5; echo "$1"; | |
} | |
#Sequential runs | |
for thing in a b c d e f g; do | |
task "$thing" | |
done | |
#Parallel runs | |
for thing in a b c d e f g; do | |
task "$thing" & | |
done | |
#Parallel runs in N-process batches | |
N=4 | |
( | |
for thing in a b c d e f g; do | |
((i=i%N)); ((i++==0)) && wait | |
task "$thing" & | |
done | |
) | |
#N processes with a FIFO-based semaphore: | |
open_sem(){ | |
mkfifo pipe-$$ | |
exec 3<>pipe-$$ | |
rm pipe-$$ | |
local i=$1 | |
for((;i>0;i--)); do | |
printf %s 000 >&3 | |
done | |
} | |
run_with_lock(){ | |
local x | |
read -u 3 -n 3 x && ((0==x)) || exit $x | |
( | |
"$@" | |
printf '%.3d' $? >&3 | |
)& | |
} | |
N=4 | |
open_sem $N | |
for thing in {a..g}; do | |
run_with_lock task $thing | |
done | |
# From https://unix.stackexchange.com/a/216475/192012 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment