2017-08-17 91 views
3

我在Erlang的文档中发现函数spawn有一个格式,如spawn(Module, Name, Args) -> pid()。我试过了。它不起作用。什么地方出了错?产卵有什么问题?

代码:

-module(tut). 

-export([main/0]). 


main() -> 
    spawner(), 
    spawner(), 
    spawner(). 

for(Counter) when Counter == 0 -> 
    io:fwrite("0"); 
for(Counter) when Counter > 0 -> 
    io:fwrite("~p\n", [Counter]), 
    for(Counter -1). 

spawner() -> 
    spawn(tut, for, [50]). 

控制台输出:

68> c(tut).  
tut.erl:12: Warning: function for/1 is unused 
{ok,tut} 
69> tut:main(). 
<0.294.0> 
=ERROR REPORT==== 6-Sep-2017::15:06:29 === 
Error in process <0.292.0> with exit value: 
{undef,[{tut,for,"2",[]}]} 
70> 
=ERROR REPORT==== 6-Sep-2017::15:06:29 === 
Error in process <0.293.0> with exit value: 
{undef,[{tut,for,"2",[]}]} 

=ERROR REPORT==== 6-Sep-2017::15:06:29 === 
Error in process <0.294.0> with exit value: 
{undef,[{tut,for,"2",[]}]} 

回答

6

spawn三个参数版本只有当你调用的函数被导出的作品。为了使它起作用,除了main之外,您还可以导出for函数,或者使用spawn的单参数版本,传递一个匿名函数(一个“fun”),这个函数会进行本地调用,从而绕过导出功能:

spawn(fun() -> for(50) end) 
+0

它是否适合导入的函数? –

+0

从'spawn(fun() - > ... end)调用导入的函数应该可以工作。三参数版本不会从导入函数中获得任何东西 - 您需要指定原始模块名称。无论如何,最好避免在Erlang中导入函数,请参阅[本答案](https://stackoverflow.com/a/36092365/113848)。 – legoscia