Skip to content

Instantly share code, notes, and snippets.

@MichaelDrogalis
Created February 6, 2013 03:12
Show Gist options
  • Save MichaelDrogalis/4719928 to your computer and use it in GitHub Desktop.
Save MichaelDrogalis/4719928 to your computer and use it in GitHub Desktop.
-module(core).
-export([front_end_task/0, task/1, main/1]).
%% Call fn
%% Get back a future
%% Dereference
%% - Blocks until if not done, then returns
%% - If done, returns immediately
task(Pid) ->
%% Maybe querying a database or something. This takes a while.
timer:sleep(3000),
Pid ! 5. %%% 5 is the result of this ficticous computation.
front_end_task() ->
spawn(core, task, [self()]),
fun() ->
receive Result ->
Result
end
end.
main(_) ->
io:format("Calling the front-end task...~n"),
Future = front_end_task(),
io:format("Got a future back. Returned immediately. Dereferencing the future...~n"),
io:format("Dereferencing returned ~w.~n", [Future()]),
io:format("Result has been returned.~n").
%% Sample run:
%% mike@nadia ~/projects/erlang-futures $ escript core.erl
%% Calling the front-end task...
%% Got a future back. Returned immediately. Dereferencing the future...
%% <Bit of a wait here>
%% Dereferencing returned 5.
%% Result has been returned.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment