Skip to content

Instantly share code, notes, and snippets.

@reasonset
Created June 6, 2016 05:13
Show Gist options
  • Save reasonset/52ec7e199d24a2f7c6c53446dbc8ad2b to your computer and use it in GitHub Desktop.
Save reasonset/52ec7e199d24a2f7c6c53446dbc8ad2b to your computer and use it in GitHub Desktop.
Multi thread programming in Zsh with Socket Queue version.
#!/usr/bin/zsh
zmodload zsh/net/socket
producer() {
typeset -i threads="$1"
typeset -i deadcount=0
shift
typeset -a myarg=("$@")
zsocket -l ~/tmp/testsock
typeset sock=$REPLY
(
while zsocket -a $sock
do
typeset fd=$REPLY
typeset narg=${myarg[1]}
if [[ -n $narg ]]
then
print "$narg" >&$fd
shift myarg
exec {fd}>&-
else
print '\000' >&$fd
(( deadcount++ ))
exec {fd}>&-
if (( deadcount >= threads ))
then
rm -v ~/tmp/testsock
break
fi
fi
done
) &
}
worker() {
worker_num=$1
while true
do
zsocket ~/tmp/testsock
typeset -i fd=$REPLY
myarg="$(<&$fd)"
exec {fd}>&-
if [[ $myarg == $'\000' ]]
then
print "Worker $worker_num ended."
break
elif [[ -z $myarg ]]
then
#CAN'T HAPPEN
print "Worker $worker_num takes EMPTY ARGUMENT!!!"
exit 127
else
print -l "Worker $worker_num: $myarg"
fi
done
}
producer 3 {1..100}
( worker 1 ) &
( worker 2 ) &
( worker 3 ) &
wait
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment