aboutsummaryrefslogtreecommitdiff
path: root/tests/benchmarks/thundering-herd/stm.go
blob: fa31938af383e9d5ff40a88a551201785a1c7eee (plain) (blame)
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
package stm

import (
	"flag"
)



var nFlag = flag.Int(
	"n",
	1_000,
	"The number of iterations to execute",
)

func MainTest() {
	flag.Parse()
	n := *nFlag

	const maxTokens = 25
	for i := 0; i < n; i++ {
		done := NewBuiltinEqVar(false)
		tokens := NewBuiltinEqVar(0)
		pending := NewBuiltinEqVar(0)
		for i := 0; i < 1000; i++ {
			Atomically(VoidOperation(func(tx *Tx) {
				pending.Set(tx, pending.Get(tx)+1)
			}))
			go func() {
				Atomically(VoidOperation(func(tx *Tx) {
					t := tokens.Get(tx)
					if t > 0 {
						tokens.Set(tx, t-1)
						pending.Set(tx, pending.Get(tx)-1)
					} else {
						tx.Retry()
					}
				}))
			}()
		}
		go func() {
			for Atomically(func(tx *Tx) bool {
				if done.Get(tx) {
					return false
				}
				tx.Assert(tokens.Get(tx) < maxTokens)
				tokens.Set(tx, tokens.Get(tx)+1)
				return true
			}) {
			}
		}()
		Atomically(VoidOperation(func(tx *Tx) {
			tx.Assert(pending.Get(tx) == 0)
		}))
		AtomicSet(done, true)
	}
}