Skip to content

Instantly share code, notes, and snippets.

@fizx
Forked from nz/named pipe queues.sh
Created January 15, 2014 01:46
Show Gist options
  • Save fizx/8429343 to your computer and use it in GitHub Desktop.
Save fizx/8429343 to your computer and use it in GitHub Desktop.
#!/bin/sh
# clear old pipe and lock
rmdir worklock 2>/dev/null
rm work
if [[ ! -p work ]]; then
mkfifo work
else
dd if=work of=/dev/null
fi
# define a worker loop
function worker {
workerid=$1
job=""
while [[ $job != "quit" ]] ; do
# acquire a really naive lock so we don't race others for the fifo
if mkdir worklock 2>/dev/null ; then
# read the job off the pipe
read job < work
# unlock the queue so others can work
rmdir worklock
# do the work
case "$job" in
"quit")
echo "worker $workerid: quitting"
;;
*)
echo "worker $workerid: $job"
sleep 3 # simulate work
;;
esac
else
# failed to get the lock, wait and try again
sleep 0.01
fi
done
}
# start two workers
worker 1 &
worker 2 &
worker 3 &
worker 4 &
# send them jobs
function queue {
echo $* >> work
sleep 0.01
}
queue "job 1"
queue "job 2"
queue "job 3"
queue "job 4"
queue "job 5"
queue "job 6"
queue "quit"
queue "quit"
queue "quit"
queue "quit"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment