Skip to content

Instantly share code, notes, and snippets.

@mloughran
Created November 4, 2011 19:36
Show Gist options
  • Save mloughran/1340275 to your computer and use it in GitHub Desktop.
Save mloughran/1340275 to your computer and use it in GitHub Desktop.

Revisions

  1. Martyn Loughran created this gist Nov 4, 2011.
    45 changes: 45 additions & 0 deletions fiber_cache.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    require 'eventmachine'
    require 'em-hiredis'
    require 'fiber'

    class Cache
    include EM::Deferrable

    def initialize(key)
    $redis.get(key) { |v|
    @value = v
    succeed
    }
    end

    def value
    if @value
    puts "Returning cached value"
    @value
    else
    puts "Blocking the current fiber till result"
    start = Time.now
    f = Fiber.current
    callback {
    puts "Fiber blocked for #{Time.now - start}s"
    f.resume(@value)
    }
    return Fiber.yield
    end
    end
    end

    EM.run {
    $redis = EM::Hiredis.connect

    Fiber.new {
    $redis.set('foo', 'hello folks')

    c = Cache.new('foo')
    p c.value # Not populated yet - will block fiber

    EM.add_timer(1) {
    p c.value # Will return from cache
    }
    }.resume
    }