Skip to content

Instantly share code, notes, and snippets.

@fsword
Forked from anonymous/multi_try.erl
Last active December 10, 2015 02:28
Show Gist options
  • Select an option

  • Save fsword/4367307 to your computer and use it in GitHub Desktop.

Select an option

Save fsword/4367307 to your computer and use it in GitHub Desktop.
-module(multi_try).
-export([dothese/1]).
dothese(FuncArray) ->
Me = self(),
lists:foreach(fun(F) -> spawn(fun() -> F(Me) end) end, FuncArray),
spawn(fun() -> timer:sleep(200), Me ! timeout end),
Result = get_result("",length(FuncArray)),
io:format("result: ~p~n", [Result]).
get_result(Result, 0) ->
Result;
get_result(Result, RemainTimes) ->
receive
timeout ->
Result;
Sth -> get_result(Result ++ Sth, RemainTimes - 1)
end.
#!/usr/bin/env escript
main(_) ->
A = fun(Pid) -> timer:sleep(100), Pid ! "A" end,
B = fun(Pid) -> timer:sleep(300), Pid ! "B" end,
C = fun(Pid) -> timer:sleep(150), Pid ! "C" end,
multi_try:dothese([A,B,C]).
@fsword
Copy link
Copy Markdown
Author

fsword commented Dec 24, 2012

之前提交成 anonymous 了,汗

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment