Skip to content

Commit

Permalink
Improve the event_catcher_spec by using a Latch
Browse files Browse the repository at this point in the history
  • Loading branch information
slyphon committed May 7, 2012
1 parent b3fab58 commit da72ce1
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 8 deletions.
7 changes: 4 additions & 3 deletions spec/event_catcher_spec.rb
Expand Up @@ -4,21 +4,22 @@
describe EventCatcher do
subject { EventCatcher.new }

let!(:latch) { Latch.new }

describe :wait_for do
it %[should wake when an event is delivered] do
pending "this has a pretty awful race in it"

th = Thread.new do
subject.synchronize do
logger.debug { "about to wait for created" }
latch.release
subject.wait_for_created
logger.debug { "woke up, created must have been delivered" }
end
true
end

th.run
Thread.pass until th.status == 'sleep'
latch.await

logger.debug { "th.status: #{th.status}" }

Expand Down
10 changes: 5 additions & 5 deletions spec/support/event_catcher.rb
Expand Up @@ -64,15 +64,15 @@ def cond_#{name}
# waits for an event group to not be empty (up to timeout sec)
def wait_for_#{name}(timeout=5)
cond(:#{name}).wait(timeout)
wait_for(:#{name}, timeout)
end
def wait_while_#{name}
cond(:#{name}).wait_while { yield __send__(:#{name}) }
def wait_while_#{name}(&blk)
wait_while(:#{name}, &blk)
end
def wait_until_#{name}
cond(:#{name}).wait_until { yield __send__(:#{name}) }
def wait_until_#{name}(&blk)
wait_until(:#{name}, &blk)
end
EOS
end
Expand Down
23 changes: 23 additions & 0 deletions spec/support/latch.rb
@@ -0,0 +1,23 @@
# the much fabled 'latch' that tenderlove and nahi were on about

class Latch
def initialize(count = 1)
@count = count
@mutex = Monitor.new
@cond = @mutex.new_cond
end

def release
@mutex.synchronize {
@count -= 1 if @count > 0
@cond.broadcast if @count.zero?
}
end

def await
@mutex.synchronize {
@cond.wait_while { @count > 0 }
}
end
end

0 comments on commit da72ce1

Please sign in to comment.