-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounters.rb
57 lines (44 loc) · 966 Bytes
/
counters.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
require 'celluloid/autostart'
class Counter
attr_reader :counter
def initialize
@counter = 0
end
# Not threadsafe!
def increment
@counter += 1
end
end
c = Counter.new
10.times.map { Thread.new { 1000.times { c.increment }} }.map(&:join)
puts c.counter
class CounterWithMutex
attr_reader :counter
def initialize
@counter = 0
@mutex = Mutex.new
end
# Threadsafe with explicit locking
def increment
@mutex.synchronize do
@counter += 1
end
end
end
cwm = CounterWithMutex.new
10.times.map { Thread.new { 1000.times { cwm.increment }} }.map(&:join)
puts cwm.counter
class CounterActor
include Celluloid
attr_reader :counter
def initialize
@counter = 0
end
# Threadsafe with implicit locking thanks to Celluloid and the Actor Model
def increment
@counter += 1
end
end
ca = CounterActor.new
10.times.map { Thread.new { 1000.times { ca.increment }} }.map(&:join)
puts ca.counter