Skip to content

Instantly share code, notes, and snippets.

@o0101
Last active November 10, 2023 09:37
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 o0101/4f2ba0239a3465827e9405caa7965969 to your computer and use it in GitHub Desktop.
Save o0101/4f2ba0239a3465827e9405caa7965969 to your computer and use it in GitHub Desktop.
with_lock: A simple Bash decorator function for concurrency control

with_lock

Simplify Bash Locking: Your Decorator for Safe Scripting

Hey, scripter! Need to make your Bash functions play nice in the concurrency sandbox? You're in luck!

with_lock is your go-to decorator. It ensures specified functions run one at a time, even across multiple script instances. 🤖

Caveats

  • It's mostly FIFO (first in, first out), but occasionally things get a bit mixed. 🤷‍♀️
  • Know a better way? Share it!

🚀 Before launching, note that this is bash-specific and assumes you're on MacOS (brew) or Debian/Ubuntu (apt). It's not a multitasking Swiss Army knife; it's your queue-forming buddy.

Quick Start

chmod +x {with_lock,test_harness.sh}
./test_harness.sh

Script Usage:

_my_func() {
  # Your logic here
}

my_func() {
  with_lock _my_func "$@"
}

# Run without worrying about overlap!
my_func "arg1" "arg2"

Try it out and let us know what you think! 🌟

This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>
#!/bin/bash
. ./with_lock
# Example usage
function my_function {
local arg1="$1"
local arg2="$2"
echo "Running my_function with arguments ${arg1} and ${arg2}"
sleep 2
echo "Finished my_function"
}
wrapper() {
with_lock "my_function" "my_function_lock" 10 "$1" "$2"
}
echo "Invoking my_function without a lock..."
for i in {1..5}; do
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
my_function "Run${i}" "$timestamp" &
done
wait
# Invoke main_script.sh concurrently 5 times
echo "Invoking with a lock..."
for i in {1..5}; do
timestamp=$(date '+%Y-%m-%d %H:%M:%S')
wrapper "Run${i}" "$timestamp" &
done
# Wait for all background jobs to complete
wait
# Check if flock is installed, if not, try to install it
if ! command -v flock &> /dev/null; then
echo "flock could not be found, attempting to install..." >&2
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# Linux
sudo apt update && sudo apt install -y flock
elif [[ "$OSTYPE" == "darwin"* ]]; then
# MacOS
brew install flock
else
echo "Unsupported OS, exiting."
exit 1
fi
if ! command -v flock &> /dev/null; then
echo "Could not install flock! Exiting..." >&2
exit 1
fi
fi
# Bash decorator for function locking
function with_lock {
local func_name="$1"
local lockfile="/tmp/${2}.lock"
local wait_time="${3:-5}" # Default wait time is 5 seconds
# Shift the first three arguments off so "$@" only includes additional arguments for the function
shift 3
(
# Try to acquire the lock
flock -w "$wait_time" 200 || {
echo "Could not acquire lock on ${lockfile}. Exiting."
exit 1
}
# Call the function with all remaining arguments
"$func_name" "$@"
) 200>"${lockfile}"
}
export -f with_lock
@o0101
Copy link
Author

o0101 commented Sep 16, 2023

This is just created! It has not been thoroughly tested, but it's the basis for something more. For some stuff it's enough as it is.

Improvements welcome!

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