Skip to content

Instantly share code, notes, and snippets.

@naufalso
Created October 11, 2024 01:55
Show Gist options
  • Save naufalso/ccf38685570ec5755af3b29bb44fb794 to your computer and use it in GitHub Desktop.
Save naufalso/ccf38685570ec5755af3b29bb44fb794 to your computer and use it in GitHub Desktop.
Paralel Queue with tmux
#!/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 in a tmux session 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
(
# Create a unique tmux session name
session_name="session_$$"
tmux new-session -d -s "$session_name" "$@"
tmux wait-for -S "$session_name"
# 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
@naufalso
Copy link
Author

TODO: test this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment