-
Notifications
You must be signed in to change notification settings - Fork 25
/
example2.rb
30 lines (27 loc) · 911 Bytes
/
example2.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
require './redlock.rb'
def thread_main(count)
dlm = Redlock.new("redis://127.0.0.1:6379","redis://127.0.0.1:6380","redis://127.0.0.1:6381")
incr=0
count.times {
my_lock = dlm.lock("foo",1000)
if my_lock
if my_lock[:validity] > 500
# Note: we assume we can do it in 500 milliseconds. If this
# assumption is not correct, the program output will not be
# correct.
number = File.read("/tmp/counter.txt")
File.write("/tmp/counter.txt",(number.to_i+1).to_s)
incr += 1
end
dlm.unlock(my_lock)
end
}
puts "/tmp/counter.txt incremented #{incr} times."
end
File.write("/tmp/counter.txt","0")
threads=[]
5.times {
threads << Thread.new{thread_main(100)}
}
threads.each{|t| t.join}
puts "Counter value is #{File.read("/tmp/counter.txt")}"