Skip to content

Instantly share code, notes, and snippets.

@ka8725
Last active January 9, 2016 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ka8725/3a3673b23447deef15cf to your computer and use it in GitHub Desktop.
Save ka8725/3a3673b23447deef15cf to your computer and use it in GitHub Desktop.
@semaphore = Mutex.new
def cache
@cache ||= {}
end
def get_y
sleep 1
Object.new
end
def read(x)
cache[x] ||= begin
y = get_y
y
end
end
def read2(x)
cache[x] ||= begin
y = get_y
cache[x] = y
end
end
def read3(x)
@semaphore.synchronize do
read(x)
end
end
10.times.map do
Thread.new do
puts read(123).object_id
end
end.each(&:join)
# 70364185000120
# 70364184999880
# 70364184999740
# 70364184999560
# 70364184999440
# 70364184999340
# 70364184999120
# 70364184998920
# 70364184998820
# 70364184998680
10.times.map do
Thread.new do
puts read(124).object_id
end
end.each(&:join)
# 70325148659660
# 70325148659060
# 70325148658860
# 70325148658380
# 70325148657920
# 70325148657380
# 70325148656320
# 70325148655840
# 70325148663580
# 70325148662820
10.times.map do
Thread.new do
puts read3(125).object_id
end
end.each(&:join)
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
# 70276222056500
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment