[英]More info about spawning functions in Erlang
I have often seen people spawning new functions with arity 0 (no arguments) as: 我经常看到人们使用Arity 0(无参数)生成如下新函数:
spawn_link(fun function_name/0).
where function_name/0 can be for example: 例如,其中function_name / 0可以是:
function_name() ->
io:format("hello~n", [])
end.
Can I spawn in a similar way a function which takes a parameter? 我可以类似的方式产生一个带有参数的函数吗? For example: 例如:
function_name(Arg) ->
io:format("hello ~p ~n", [Arg])
end.
Should I use 我应该使用
spawn_link(Module, Function, Arg)
or something else? 或者是其他东西?
You can use that spawn_link
with arguments, build a lambda function ( fun
) with the specified arguments or just with fixed ones. 您可以将spawn_link
与参数一起使用,使用指定的参数或仅使用固定的参数来构建lambda函数( fun
)。 So for example you could use, as you say, just: 因此,例如,您可以使用如您所说的:
spawn_link(Module, Function, Args).
or export your own spawn_link
(or start
) in your module: 或在模块中导出自己的spawn_link
(或start
):
spawn_link(Args) ->
spawn_link(?MODULE, fun myfun/X, Args).
or use a fun
: 或fun
:
spawn_link(Args) ->
spawn_link(fun () -> apply(fun myfun/X, Args) end).
or if you internally call some function with fixed parameters: 或者如果您在内部使用固定参数调用某些函数:
spawn_link() ->
spawn_link(fun () -> myfun(1,2,3) end).
where X
in this case is the arity of the myfun
function in each case. 其中,在这种情况下, X
是myfun
函数的myfun
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.