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