Created
December 24, 2012 03:18
-
-
Save anonymous/4367305 to your computer and use it in GitHub Desktop.
实现一个API,API内部有两个http接口A,B并发调用,如果都在200ms内返回,则合并结果输出,如果B比A慢,且B耗时超过200ms,则丢弃B调用只返回A结果
This file contains 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(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. |
This file contains 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
#!/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]). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
200毫秒吗?我写成1000毫秒了,逻辑在这里