forked from igrigorik/em-synchrony
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add fiber iterator: each block is wrapped in a fiber + auto-advance
- Loading branch information
Showing
3 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
module EventMachine | ||
module Synchrony | ||
|
||
class FiberIterator < EM::Synchrony::Iterator | ||
|
||
# execute each iterator block within its own fiber | ||
# and auto-advance the iterator after each call | ||
def each(foreach=nil, after=nil, &blk) | ||
fe = Proc.new do |obj, iter| | ||
Fiber.new { (foreach || blk).call(obj); iter.next }.resume | ||
end | ||
|
||
super(fe, after) | ||
end | ||
|
||
end | ||
end | ||
end |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
require "spec/helper/all" | ||
require "em-synchrony/fiber_iterator" | ||
|
||
describe EventMachine::Synchrony::FiberIterator do | ||
|
||
it "should wait until the iterator is done and wrap internal block within a fiber" do | ||
EM.synchrony do | ||
|
||
results = [] | ||
i = EM::Synchrony::FiberIterator.new(1..5, 2).each do |num| | ||
EM::Synchrony.sleep(0.1) | ||
results.push num | ||
end | ||
|
||
results.should == (1..5).to_a | ||
results.size.should == 5 | ||
EventMachine.stop | ||
end | ||
end | ||
|
||
# | ||
# it "should sum values within the iterator" do | ||
# EM.synchrony do | ||
# data = (1..5).to_a | ||
# res = EM::Synchrony::FiberIterator.new(data, 2).inject(0) do |total, num, iter| | ||
# EM::Synchrony.sleep(0.1) | ||
# | ||
# p [:sync, total, num] | ||
# iter.return(total += num) | ||
# end | ||
# | ||
# res.should == data.inject(:+) | ||
# EventMachine.stop | ||
# end | ||
# end | ||
|
||
|
||
|
||
end |