-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXX_tabla.rb
59 lines (51 loc) · 905 Bytes
/
XX_tabla.rb
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
class Table
def initialize(hash)
@hash = hash
@lock = Mutex.new
end
def put(key, value)
@lock.synchronize do
@hash[key] = value
end
end
def get(key)
@lock.synchronize do
@hash[key]
end
end
def accum(key, delta)
v = get(key) + delta
put(key, v)
end
end
def concurrent_test(count)
table = Table.new({counter: 0})
(1..count).map do |it|
if it.even?
Thread.new do
table.put(:counter, 1)
end
else
Thread.new do
v = table.get(:counter)
table.put(:counter, 2)
end
end
end.each(&:join)
table
end
def concurrent_test2(count)
table = Table.new({counter: 0})
(1..count).map do |it|
if it.even?
Thread.new do
table.accum(:counter, 1)
end
else
Thread.new do
table.accum(:counter, -1)
end
end
end.each(&:join)
table
end