future.monkey2 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. Namespace std.fiber
  2. #if __TARGET__<>"emscripten"
  3. #rem monkeydoc Futures provide support for simple fiber synchronization.
  4. A future allows you to synchronize two fibers by providing a way for one fiber to signal to another that an operation has completed.
  5. The general usage pattern of futures is:
  6. * Fiber A creates a future and passes it to fiber B.
  7. * Fiber A then calls [[Get]] on the future. This will suspend Fiber A.
  8. * Fiber B performs some operation, then calls [[Set]] on the future. This will resume Fiber A.
  9. A future can only be set once.
  10. #end
  11. Class Future<T>
  12. #rem monkeydoc Creates a new future.
  13. #end
  14. Method New()
  15. _fiber=Fiber.Current()
  16. End
  17. #rem monkeydoc Sets the future's value.
  18. #end
  19. Method Set( value:T )
  20. DebugAssert( Not _ready,"Future has already be set" )
  21. _value=value
  22. _ready=True
  23. If _waiting _fiber.Resume()
  24. End
  25. #rem monkeydoc Gets the future's value.
  26. #end
  27. Method Get:T()
  28. If Not _ready
  29. _waiting=True
  30. Fiber.Suspend()
  31. _waiting=false
  32. Endif
  33. Return _value
  34. End
  35. Private
  36. Field _fiber:Fiber
  37. Field _value:T
  38. Field _ready:Bool
  39. Field _waiting:Bool
  40. End
  41. #endif