# sync-defer <https://github.com/godfat/sync-defer>
by Lin Jen-Shin ([godfat](http://godfat.org))
## DESCRIPTION:
Synchronous deferred operations with fibers (coroutines)
## INSTALLATION:
gem install sync-defer
### SYNOPSIS:
Remember to wrap a fiber around the client, and inside the client:
* Generic interface which would select underneath reactor
automatically:
# Single computation:
puts(SyncDefer.defer{
sleep(5) # any CPU-bound operations
100}) # 100
puts "DONE"
# Multiple computations:
puts(SyncDefer.defer(lambda{
sleep(5) # any CPU-bound operations
100
},
lambda{
sleep(2) # any CPU-bound operations
50})) # [100, 50] # it would match the
index
puts "DONE"
Full examples with reactor turned on:
* with cool.io:
# only for adding at least one watcher in the loop
Coolio::TimerWatcher.new(1).
attach(Coolio::Loop.default).on_timer{detach}
Fiber.new{
# or Coolio::SyncDefer
SyncDefer.defer{ sleep(5) }
puts "DONE"
}.resume
Coolio::Loop.default.run
* with eventmachine:
EM.run{
Fiber.new{
# or EM::SyncDefer
SyncDefer.defer{ sleep(5) }
puts "DONE"
EM.stop
}.resume
}
* No problems with exceptions, use them as normal:
EM.run{
Fiber.new{
begin
SyncDefer.defer{ raise "BOOM" }
rescue => e
p e
end
EM.stop
}.resume
}
## CHANGES:
### sync-defer 0.9.2 -- 2012-03-20
* Properly select the reactor.
* Made it exception aware. If there's an exception raised in the
computation, sync-defer would resume back and raise that exception.