Created
November 10, 2009 04:55
-
-
Save arya/230638 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'memcached' | |
def sleep_for(count) | |
sleep((2**count) / 2.0) | |
# sleep (1 / (count + 1).to_f) * 0.6 | |
# sleep [0.2, (rand / 3)].max | |
end | |
class Error < Exception; end | |
def acquire_lock(memcache, key, retries = 100) | |
retries.times do |count| | |
begin | |
response = begin | |
memcache.add("#{key}", Process.pid, 10000) | |
return true | |
rescue Memcached::NotStored | |
raise Error if count == retries - 1 | |
end | |
end | |
sleep_for(count) unless count == retries - 1 | |
end | |
raise Error, "Couldn't acquire memcache lock for: #{key}" | |
end | |
start_time = 0 | |
end_time = 2000 | |
every = 100 | |
duration = 250 | |
memcache = Memcached.new(["localhost:11211"], :namespace => "testing") | |
start_at = Time.now.to_f + 2 | |
key = "TestKey" | |
forks = (end_time - start_time) / every | |
forks.times do |i| | |
if fork | |
else | |
memcache.reset | |
my_delay = (every * i) / 1000.0 | |
sleep((start_at - Time.now.to_f) + my_delay) | |
begin | |
acquire_lock(memcache, key) | |
rescue Error | |
puts "Failed to acquire lock: #{i}" | |
exit | |
end | |
puts "Acquired lock: #{i}" | |
sleep duration / 1000.0 | |
memcache.delete(key) | |
exit | |
end | |
end | |
Process.waitall | |
puts "%.5f" % (Time.now.to_f - start_at) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment