Skip to content

Instantly share code, notes, and snippets.

@YurySolovyov
Created February 19, 2016 21:13
Show Gist options
  • Save YurySolovyov/ccd7799342f0392d93fa to your computer and use it in GitHub Desktop.
Save YurySolovyov/ccd7799342f0392d93fa to your computer and use it in GitHub Desktop.
threads.ruby
require "rack"
require "json"
use Rack::ContentLength
use Rack::Logger, Logger.new(STDOUT)
use Rack::Static, :urls => ["/static"]
module CacheHolder
CACHE = Hash.new
LOCK = Mutex.new
def self.get(key)
LOCK.synchronize do
CACHE.fetch(key, nil)
end
end
def self.set(key, value)
LOCK.synchronize do
CACHE[key] = value
end
end
def self.get_cache_key(request)
"#{request['type']}//#{request['SERVER_PROTOCOL']}//#{'->' * 3}"
end
end
class Responder
def initialize(env)
@request = Rack::Request.new(env)
@param = @request['type']
end
def try_get_value
time = Random.rand(0.5)
p "Sleeping #{time}. sec"
sleep time
key = CacheHolder.get_cache_key(@request)
value = CacheHolder.get(key)
if value.nil?
value = get_value_slow
CacheHolder.set(key, value)
end
value
end
def get_value_slow
time = Random.rand(10)
p "Sleeping #{time}. sec"
sleep time
"#{'#' * 1000}"
end
def each
@body = { param: @param, value: try_get_value }
yield @body.to_json
end
end
app = proc do |env|
[ 200, {'Content-Type' => 'text/json' }, Responder.new(env) ]
end
run app
request = function() {
'use strict';
return Promise.all([
$.getJSON('http://localhost:9292/', { type: 'documents' }),
$.getJSON('http://localhost:9292/', { type: 'projects' }),
]).then(function(res) {
if (res[0].param !== 'documents' || res[1].param !== 'projects') {
console.log('race ->', res[0].context, res[1].context )
}
});
}
Promise.all(_.times(100, request)).then(()=> { console.log('done') })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment