Skip to content

Instantly share code, notes, and snippets.

@buger
Last active August 26, 2021 18:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buger/617fe26794c4358460ce69864a61b8a9 to your computer and use it in GitHub Desktop.
Save buger/617fe26794c4358460ce69864a61b8a9 to your computer and use it in GitHub Desktop.
Bash atomic counter
# See http://wiki.bash-hackers.org/howto/mutex for more details
lock() {
if mkdir $1 &> /dev/null; then
return 0
else
r=$(($2 + 0))
# timeout after 5 retries
if [ "$r" -gt "5" ]; then
echo "Lock failed:" $1
return 1
fi
sleep 0.1
lock $1 $(($2 + 1))
return $?
fi
}
unlock(){
rm -rf $1
}
lock /tmp/counter-lock
c=$(cat /tmp/counter 2> /dev/null)
c=$((c + 0)) # if counter is empty, initialize it
echo $((c+1)) > /tmp/counter
unlock /tmp/counter-lock
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment