-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmutex_counter_ex
More file actions
executable file
·60 lines (45 loc) · 1.17 KB
/
mutex_counter_ex
File metadata and controls
executable file
·60 lines (45 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/bin/bash
#
# Example inspired by mutex-counter.go from the Go tutorial
# (https://go.dev/tour/concurrency/9).
readonly DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
. ${DIR}/../gobash
function SafeCounter() {
# Including mutex as one of the fields.
make_ $FUNCNAME \
"mu" "$(Mutex)" \
"v" "$(Map)"
}
function SafeCounter_inc() {
local -r c="${1}"
local -r key="${2}"
shift 2
# Lock mutex kept in this instance.
$($c mu) lock
$($c v) inc "${key}"
# Unlock when the work is done.
$($c mu) unlock
}
function SafeCounter_value() {
local -r c="${1}"
local -r key="${2}"
shift 2
$($c mu) lock
local res=$($($c v) get "${key}")
$($c mu) unlock
echo "${res}"
}
function main() {
local c
c=$(SafeCounter) || assert_fail
echo "Run increment in parallel with 10 subshells."
for (( i=0; i<10; i++ )); do
( $c inc "somekey" ) &
done
echo "Wait for subshells to be done."
wait || assert_fail
$c value "somekey"
}
main
# Output will be:
# 10