-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRead-Write-Lock.rb
More file actions
84 lines (64 loc) · 954 Bytes
/
Read-Write-Lock.rb
File metadata and controls
84 lines (64 loc) · 954 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
require "pp"
require "sync"
class ReadWriteLock
include Sync_m
def initialize
super
@word =""
end
def read(name)
sync_synchronize(:SH){
puts("#{name},read:#{@word}")
}
sleep(rand(2))
nil
end
def write(data)
sync_synchronize(:EX){
puts("write:#{data}")
@word+=data
}
sleep(rand(2))
nil
end
end
class Main
def initialize(thread)
@thread = thread
end
def read(name)
@thread.read(name)
end
def write(data)
@thread.write(data)
end
end
thread = ReadWriteLock.new
thread1 = Main.new(thread)
thread2 = Main.new(thread)
thread3 = Main.new(thread)
t1=Thread.new{
i=0
loop do
thread.write(((i+=1)%10).to_s)
end
}
t2=Thread.new{
loop do
thread1.read("Thread1")
end
}
t3=Thread.new{
loop do
thread2.read("Thread2")
end
}
t4=Thread.new{
loop do
thread3.read("Thread3")
end
}
t1.join
t2.join
t3.join
t4.join