Created
March 3, 2014 07:30
-
-
Save k33g/9320023 to your computer and use it in GitHub Desktop.
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 futures | |
| import gololang.Async | |
| import java.util.concurrent.TimeUnit | |
| import java.util.concurrent.Executors | |
| import java.lang.Math | |
| # Properties | |
| struct promiseStructure = { | |
| promise | |
| , callback | |
| , executor | |
| } | |
| # Methods | |
| augment futures.types.promiseStructure { | |
| function task = |this, work| { #this is a setter | |
| this: promise(): future(): onSet(work) | |
| return this | |
| } | |
| function done = |this, callback| { #this is a setter | |
| this: callback(callback) | |
| return this | |
| } | |
| function submit = |this, value| { | |
| this: executor(): submit({ | |
| this: promise(): set(value) | |
| this: callback()(this: promise(): get()) | |
| }) | |
| } | |
| } | |
| # Constructor | |
| function Promise = |executor| { | |
| return promiseStructure(promise(), null, executor) | |
| } | |
| struct value = { parameter, result, start, end } | |
| function piCalculus = |howManyIterations| { | |
| let startTime = System.currentTimeMillis() | |
| var unQuartDePi = 0.0 | |
| var pi = 0.0 | |
| var k = 0.0 | |
| let term = |k| ->(Math.pow(-1.0, k))/(2*k+1) | |
| for (var i = 0, i < howManyIterations, i = i + 1) { | |
| unQuartDePi = unQuartDePi + term(k) | |
| pi = 4 * unQuartDePi | |
| k=k+1.0 | |
| } | |
| return pi | |
| } | |
| function main = |args| { | |
| let executor = Executors.newCachedThreadPool() | |
| let p1 = Promise(executor) | |
| : task(|value| { | |
| value: result(piCalculus(value: parameter())) | |
| }) | |
| : done(|value| { | |
| value: end(System.currentTimeMillis()) | |
| println( | |
| "Pi = " + value: result() + | |
| " Duration = " + (value: end() - value: start()) + | |
| " ms Iterations = " + value: parameter() | |
| ) | |
| }) | |
| : submit(value() | |
| : parameter(10000) | |
| : start(System.currentTimeMillis() | |
| )) | |
| let p2 = Promise(executor) | |
| : task(|value| { | |
| value: result(piCalculus(value: parameter())) | |
| }) | |
| : done(|value| { | |
| value: end(System.currentTimeMillis()) | |
| println( | |
| "Pi = " + value: result() + | |
| " Duration = " + (value: end() - value: start()) + | |
| " ms Iterations = " + value: parameter() | |
| ) | |
| }) | |
| : submit(value() | |
| : parameter(1500) | |
| : start(System.currentTimeMillis() | |
| )) | |
| executor: shutdown() | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment