summaryrefslogtreecommitdiff
path: root/lib/thread/test/condvar.myr
blob: 0f1de58ea1a97de17501be74648c5c00050dfecb (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use std
use thread

use "util"

const Nwakes = 1000

var cv
var mtx
var val

var done : int32
var nwoken : int32
var nready : int32
var locked : int32

const main = {
	done = 0
	val = 123

	mtx = thread.mkmtx()
	cv = thread.mkcond(&mtx)
	thread.spawn(cvwait)
	thread.spawn(cvwake)
	while done == 0
		/* nothing */
	;;
	std.assert(nwoken == Nwakes, "wrong number of wakes")
	std.assert(val == 123, "wrong val after all are done")

	nwoken = 0
	nready = 0
	mkherd(100, cvwaitonce)

	/* wait until the herd is ready */
	while nready != 100	/* 0 to 99 */
		/* nothing */
	;;
	while locked == 0
		/* nothing */
	;;
	thread.condbroadcast(&cv)
	while nwoken != 100
		/* nothing */
	;;
	std.assert(nwoken == 100, "wrong thread count woken")

}

const cvwait = {
	for var i = 0; i < Nwakes; i++
		thread.mtxlock(&mtx)
		thread.condwait(&cv)
		std.assert(val == 456, "wrong val after signal\n")
		val = 123
		thread.mtxunlock(&mtx)

		thread.xadd(&nwoken, 1)
	;;
	val = 123
	thread.xadd(&done, 1)

}

const cvwake = {
	while true
		thread.mtxlock(&mtx)
		val = 456
		thread.mtxunlock(&mtx)

		thread.condsignal(&cv)
		if nwoken >= Nwakes
			break
		;;
	;;
}

const cvwaitonce = {
	thread.xadd(&nready, 1)

	thread.mtxlock(&mtx)
	thread.xadd(&locked, 1)
	thread.condwait(&cv)
	thread.mtxunlock(&mtx)

	thread.xadd(&nwoken, 1)
}