Last active
August 29, 2015 13:56
-
-
Save k33g/9327906 to your computer and use it in GitHub Desktop.
futures.right.way.i.hope
This file contains hidden or 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
| module m33ki.hopes | |
| import gololang.Async | |
| import java.util.concurrent.TimeUnit | |
| import java.util.concurrent.Executors | |
| import java.util.concurrent.Semaphore | |
| # Properties | |
| struct hopeStructure = { | |
| promise | |
| , task | |
| , executor | |
| } | |
| # Methods | |
| augment m33ki.hopes.types.hopeStructure { | |
| function todo = |this, task2run| { # this is a setter | |
| this: task(task2run) | |
| return this | |
| } | |
| function done = |this, callbackWhenDone| { # this is a setter | |
| this: promise(): future(): onSet(callbackWhenDone) | |
| return this | |
| } | |
| function go = |this, value| { | |
| this: executor(): submit({ | |
| this: promise(): set(this: task()(value)) | |
| }) | |
| return this | |
| } | |
| } | |
| # Constructor | |
| function Hope = |executor| { | |
| return hopeStructure(promise(), null, executor) | |
| } | |
| # utility | |
| struct vo = { value } | |
| augment m33ki.hopes.types.vo { | |
| function multiply = |this, n| -> this: value(this: value()*n) | |
| } | |
| function main = |args| { | |
| let executor = Executors.newCachedThreadPool() | |
| let hope1 = Hope(executor) | |
| : todo(|x| { | |
| let v = vo(1) | |
| x: times(|index|{ | |
| println("from hope1 : " + index) | |
| v: multiply(index+1) | |
| java.lang.Thread.sleep(500_L) | |
| }) | |
| return v: value() | |
| }) | |
| : done(|x|->println("result of hope1 : " + x)) | |
| : go(5) | |
| let hope2 = Hope(executor) | |
| : todo(|x| { | |
| let v = vo(1) | |
| x: times(|index|{ | |
| println("from hope2 : " + index) | |
| v: multiply(index+1) | |
| java.lang.Thread.sleep(500_L) | |
| }) | |
| println(v: value()) | |
| return v: value() | |
| }) | |
| : done(|x|->println("result of hope2 : " + x)) | |
| : go(6) | |
| executor: shutdown() | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment