Last active
April 16, 2020 18:30
-
-
Save curiositycasualty/25c0a2abe86df9cc13047c12bacc7abf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# set -x | |
set -m | |
# bash strict mode | |
set -euo pipefail | |
max_workers=$(( $(nproc) * 2 )) | |
lock_name='negotiation' | |
lock_dir='/tmp' | |
lock_timeout=60 | |
lock_prefix="${lock_dir}/${lock_name}_" | |
for id in $(seq 1 "$max_workers"); do | |
touch "${lock_prefix}${id}" | |
done | |
function main() { | |
lock_id=1 | |
# 20 simulated tasks | |
for i in $(seq 1 20); do | |
rand=$(( RANDOM % 10 )) | |
task="sleep ${rand} && echo '" | |
lock_file="${lock_prefix}${lock_id}" | |
echo "task: ${i} ('${task}') ${lock_file}" | |
flock -w "$lock_timeout" -x "$lock_file" -c "${task} sleep of ${rand} w/ lock: ${lock_file}'" & | |
lock_id=$(( lock_id + 1 )) | |
if [ "$lock_id" -ge "$max_workers" ]; then | |
lock_id=1 | |
fi | |
done | |
wait | |
rm -fv ${lock_prefix}* | |
} | |
main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment