-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmutex-example.lua
More file actions
62 lines (58 loc) · 1.31 KB
/
mutex-example.lua
File metadata and controls
62 lines (58 loc) · 1.31 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
61
62
local cqueues = require "cqueues"
local condition = require "cqueues.condition"
local pgsql = require "cqueues_pgsql"
local conn = pgsql.connectdb ""
if conn:status() ~= pgsql.CONNECTION_OK then
error(conn:errorMessage(), nil)
end
assert(conn:exec("LISTEN somechannel"):status() == pgsql.PGRES_COMMAND_OK)
local loop = cqueues.new()
local mutex do
mutex = {
cond = condition.new(true);
inuse = false;
}
function mutex:lock(timeout)
if self.inuse then
self.inuse = self.cond:wait(timeout)
else
self.inuse = true
end
return self.inuse
end
function mutex:unlock()
self.inuse = false
self.cond:signal(1)
end
end
loop:wrap(function()
while true do
assert(mutex:lock())
print("NUMBER 1 PRE")
local res = conn:exec("SELECT * FROM sometable")
if res == nil or res:status() ~= pgsql.PGRES_TUPLES_OK then
local err = conn:errorMessage()
mutex:unlock()
error(err)
end
print("NUMBER 1 POST")
mutex:unlock()
cqueues.sleep(1)
end
end)
loop:wrap(function()
while true do
assert(mutex:lock())
print("NUMBER 2 PRE")
local res = conn:exec("SELECT * FROM sometable")
if res == nil or res:status() ~= pgsql.PGRES_TUPLES_OK then
local err = conn:errorMessage()
mutex:unlock()
error(err)
end
print("NUMBER 2 POST")
mutex:unlock()
cqueues.sleep(2)
end
end)
assert(loop:loop())