aboutsummaryrefslogtreecommitdiff
path: root/tests/benchmarks/ping-pong/stm.go
blob: 6631ea84ae264541f60fc9f958f52903e21b8947 (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
57
58
59
package stm

import (
	"flag"
	"sync"
)



func testPingPong(n int, afterHit func(string)) {
	ball := NewBuiltinEqVar(false)
	doneVar := NewVar(false)
	hits := NewVar(0)
	ready := NewVar(true) // The ball is ready for hitting.
	var wg sync.WaitGroup
	bat := func(from, to bool, noise string) {
		defer wg.Done()
		for !Atomically(func(tx *Tx) any {
			if doneVar.Get(tx) {
				return true
			}
			tx.Assert(ready.Get(tx))
			if ball.Get(tx) == from {
				ball.Set(tx, to)
				hits.Set(tx, hits.Get(tx)+1)
				ready.Set(tx, false)
				return false
			}
			return tx.Retry()
		}).(bool) {
			afterHit(noise)
			AtomicSet(ready, true)
		}
	}
	wg.Add(2)
	go bat(false, true, "ping!")
	go bat(true, false, "pong!")
	Atomically(VoidOperation(func(tx *Tx) {
		tx.Assert(hits.Get(tx) >= n)
		doneVar.Set(tx, true)
	}))
	wg.Wait()
}


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

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

	for i := 0; i < n; i++ {
		testPingPong(n, func(string) {})
	}
}