Skip to content

Instantly share code, notes, and snippets.

@norman
Created April 8, 2013 22:24
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 norman/5341083 to your computer and use it in GitHub Desktop.
Save norman/5341083 to your computer and use it in GitHub Desktop.
require "ffaker"
require 'thread'
class ConcurrentHash
def initialize
@reader, @writer = {}, {}
@lock = Mutex.new
end
def [](key)
@reader[key]
end
def []=(key, value)
@lock.synchronize {
@writer[key] = value
@reader, @writer = @writer, @reader
@writer[key] = value
}
end
end
names = []
DupError = Class.new(StandardError)
def unique(values, &block)
value = nil
loop do
begin
value = yield
raise DupError if values[value]
values[value] = true
break
rescue DupError
print "DUP #{value}\n"
retry
end
end
value
end
cached_values = ConcurrentHash.new
20.times.map do
Thread.new do
5000.times do
names << unique(cached_values) do
"#{Faker::Name.first_name} #{Faker::Name.last_name}"
end
end
end
end.map(&:join)
puts names.count, names.uniq.count
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment