File: 61-multiwriters.lua

package info (click to toggle)
lua-cqueues 20161214-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,672 kB
  • ctags: 3,228
  • sloc: ansic: 20,232; sh: 2,959; makefile: 24
file content (98 lines) | stat: -rwxr-xr-x 1,661 bytes parent folder | download | duplicates (4)
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
89
90
91
92
93
94
95
96
97
98
#!/bin/sh
_=[[
	. "${0%%/*}/regress.sh"
	exec runlua "$0" "$@"
]]
require"regress".export".*"

local main = cqueues.new()

local _cache = {}
local function megarep(s)
	if not _cache[s] then
		_cache[s] = string.rep(string.rep(s, 1024), 1024)
	end

	return _cache[s]
end

local function test(bufsiz)
	local loop = cqueues.new()

	local rd, wr = check(socket.pair())

	wr:setvbuf("full", bufsiz)

	local sem = { count = 0, condvar = condition.new() }

	local function sem_get()
		while sem.count < 1 do
			sem.condvar:wait()
		end

		sem.count = sem.count - 1
		sem.condvar:signal()
		cqueues.sleep(0)
	end

	local function sem_put(n)
		sem.count = sem.count + (n or 1)
		sem.condvar:signal()
		cqueues.sleep(0)
	end

	for i=0,3 do
		loop:wrap(function ()
			sem_get()

			local ch = string.char(string.byte"A" + i)

			for i=1,10 do
				check(wr:write(megarep(ch)))
			end

			check(wr:flush())

			sem_put()
		end)
	end

	loop:wrap(function ()
		sem_put(4)

		repeat
			sem.condvar:wait()
		until sem.count == 4

		wr:shutdown"rw"
	end)

	local interleaved = false

	loop:wrap(function ()
		while true do
			local buf = rd:read(1024 * 1024)
			if buf == nil then break end
			local ch = string.sub(buf, 1, 1)
			local uniform = not buf:match(string.format("[^%s]", ch))

			interleaved = interleaved or not uniform

			info("read %d bytes (interleaved:%s)", #buf, tostring(not uniform))
		end
	end)

	check(loop:loop())

	return interleaved
end

info"begin control test"
check(test(4096) == true, "expected control test to interleave")
info"control test OK"

info"begin test case"
check(test(-1) == false, "test case interleaved")
info"test case OK"

say("OK")