gpt4 book ai didi

erlang - erlang :trace/3? 中的选项 "return_to"是什么意思

转载 作者:行者123 更新时间:2023-12-02 04:54:08 24 4
gpt4 key购买 nike

在 erlang 文档中:

return_to Used in conjunction with the call trace flag. Trace the actual return from a traced function back to its caller. Only works for functions traced with the local option to erlang:trace_pattern/3.

The semantics is that a trace message is sent when a call traced function actually returns, that is, when a chain of tail recursive calls is ended. There will be only one trace message sent per chain of tail recursive calls, why the properties of tail recursiveness for function calls are kept while tracing with this flag. Using call and return_to trace together makes it possible to know exactly in which function a process executes at any time.

To get trace messages containing return values from functions, use the {return_trace} match_spec action instead.

Message tags: return_to.

什么是“实际返回”?我测试了一个尾递归函数,但似乎没有什么区别。

以下是我的test.erl:

-module(test).

-compile(export_all).

-record(state, {stacks=[]}).

test_tracer() ->
Tracer = spawn_tracer(),
erlang:trace_pattern({?MODULE, '_', '_'}, [], [local]),
erlang:trace(self(), true, [call,
arity,
return_to,
%% procs,
%% running,
timestamp,
{tracer, Tracer}]),
loop(100),
Tracer!dump.

spawn_tracer() ->
spawn(fun()-> trace_listener(#state{}) end).

trace_listener(State) ->
receive
dump ->
io:format("~p", [lists:reverse(State#state.stacks)]);
{trace_ts, Pid, call, MFA, Ts} ->
Stacks = State#state.stacks,
trace_listener(State#state{stacks=[MFA|Stacks]});
_Term ->
io:format("~p~n", [_Term]),
trace_listener(State)
end.

loop(0) -> ok;
loop(N) -> loop(N-1).

无论是否有return_to,都会打印101 {test,loop,1}

我认为它应该只返回一个 {test,loop,1}return_to

最佳答案

不,return_to 标志不会禁用尾调用,它只是跟踪最终结果返回的位置/对象。

更改代码以适应屏幕:

...
loop(10),
timer:sleep(100),
Tracer ! dump.

启用 return_to 后,您将收到消息:

{trace_ts,<0.348.0>,return_to,{test,test_tracer,0},{1405,153820,908198}}

这意味着 loop/1 函数将其结果返回给 test:test_tracer/0。

没有return_to就没有这样的消息。

要获取返回值,您需要更改模式:

erlang:trace_pattern({?MODULE, '_', '_'}, [{'_', [], [{return_trace}]}], [local]),

现在您将收到如下消息:

{trace_ts,<0.657.0>,return_from,{test,loop,1},ok,{1405,155132,517284}}

关于erlang - erlang :trace/3? 中的选项 "return_to"是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24692512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com