This repository was archived by the owner on Nov 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclock.lua
More file actions
76 lines (65 loc) · 1.84 KB
/
clock.lua
File metadata and controls
76 lines (65 loc) · 1.84 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
--[[
This examples implements a global synchronization clock
using the basic LuaPi primitives.
In bclock.lua we illustrate the use of the broadcast primitives
to encode a similar pattern in a more succint way.
]]
require "pithreads"
-- the number of worker threadesses
NB_WORKERS = tonumber(arg and arg[1]) or 5
-- the clock lifetime
TIME_TO_LIVE = tonumber(arg and arg[2]) or 3
-- the worker behavior
function Worker(thread,id,register,tick,barrier,work)
thread:send(register,id)
while true do
-- wait for the next tick
local count = thread:receive(tick)
print(thread.name,"Tick #",count," received")
-- perform some work
work(thread,id,count)
-- enter the synchronization barrier
thread:send(barrier,id)
end
end
-- the global clock behavior
function Clock(thread,register,tick,barrier,nbReg,ttl)
for count=1,ttl do
if nbReg==0 then
return
end
-- emit the tick
for i=1,nbReg do
thread:send(tick,count)
end
-- synchronization barrier
for i=1,nbReg do
local pid = thread:receive(barrier)
print("Worker #",pid," synchronized")
end
-- allow some new registrations
while thread:tryReceive(register) do
nbReg = nbReg + 1
end
end
end
-- Initial registrations of workers
function Init(thread,register,tick,barrier)
local nbReg = 0
thread:yield()
while thread:tryReceive(register) do
thread:yield()
nbReg = nbReg + 1
end
thread:spawn("Clock",Clock,register,tick,barrier,nbReg,TIME_TO_LIVE)
end
agent = pithreads.init()
register = agent:new("register")
tick = agent:new("tick")
barrier = agent:new("barrier")
agent:replicate("Worker",NB_WORKERS,Worker,register,tick,barrier,
function(thread,id,tick)
print("Worker #",id," works at tick=",tick)
end)
agent:spawn("Init",Init,register,tick,barrier)
agent:run()