-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path010_check_then_set_mutex.rb
More file actions
61 lines (49 loc) · 983 Bytes
/
010_check_then_set_mutex.rb
File metadata and controls
61 lines (49 loc) · 983 Bytes
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
class Order
attr_accessor :amount, :status
def initialize(amount, status)
@amount, @status = amount, status
@mutex = Mutex.new
end
def pending?
status == 'pending'
end
def collect_payment
@mutex.synchronize do
puts 'Order: Collecting payment...'
self.status = 'paid'
end
end
end
class Order2
attr_accessor :amount, :status
def initialize(amount, status)
@amount, @status = amount, status
end
def pending?
status == 'pending'
end
def collect_payment
puts 'Order2: Collecting payment...'
self.status = 'paid'
end
end
# ------ main ------
order = Order.new(100.00, 'pending')
order2 = Order2.new(100.00, 'pending')
5.times.map do
Thread.new do
if order.pending?
order.collect_payment
end
end
end.each(&:join)
mutex = Mutex.new
5.times.map do
Thread.new do
mutex.synchronize do
if order2.pending?
order2.collect_payment
end
end
end
end.each(&:join)