Skip to content

Instantly share code, notes, and snippets.

Created December 24, 2012 03:18
Show Gist options
  • Save anonymous/4367305 to your computer and use it in GitHub Desktop.
Save anonymous/4367305 to your computer and use it in GitHub Desktop.
实现一个API,API内部有两个http接口A,B并发调用,如果都在200ms内返回,则合并结果输出,如果B比A慢,且B耗时超过200ms,则丢弃B调用只返回A结果
-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(1000), 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(200), Pid ! "A" end,
B = fun(Pid) -> timer:sleep(1200), Pid ! "B" end,
C = fun(Pid) -> timer:sleep(500), Pid ! "C" end,
multi_try:dothese([A,B,C]).
@hugozhu
Copy link

hugozhu commented Dec 24, 2012

没有看到如果B比A慢,且超过200ms时候,丢弃B调用的相关逻辑

@fsword
Copy link

fsword commented Dec 24, 2012

200毫秒吗?我写成1000毫秒了,逻辑在这里

spawn(fun() -> timer:sleep(1000), Me ! timeout end),

@fsword
Copy link

fsword commented Dec 24, 2012

修改成 200ms 了,更新到 https://gist.github.com/4367307

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