简体   繁体   English

Erlang函数调用 - 为什么调用self()作为直接参数不起作用?

[英]Erlang function calls - Why does it not work to call self() as a direct argument?

Me and my friend was trying to find a bug with our code for some time when we realised that this was the problem: 当我们意识到这是问题时,我和我的朋友试图在我们的代码中找到一个错误。

random_function(spawn_link(fun() -> worker(List, self(), Death) end));

This was the solution: 这是解决方案:

PID = self(),
random_function(spawn_link(fun() -> worker(List, PID, Death) end));

So my question is, why did it not work to just call the self()-function straight away like that? 所以我的问题是,为什么不能直接调用self()函数呢? Is it because it's an anonymous function or is it some kind of special Erlang thing? 是因为它是一个匿名函数还是某种特殊的Erlang?

It is a bit more subtle. 它有点微妙。 The self() call happens inside the fun() which is spawned. self()调用发生在fun()内部。 Since it it spawned, it has another Pid than the one you expect. 由于它产生了它,它有另一个Pid而不是你期望的Pid。 Hence, the semantics are different. 因此,语义是不同的。

you should know that spawn_link(fun() -> worker(List, self(), Death) will create a new process, we just call it Pid1 , then self() stands for Pid1 . 你应该知道spawn_link(fun() -> worker(List, self(), Death)会创建一个新进程,我们只称它为Pid1 ,然后self()代表Pid1

In the second case, you can Pid = self() outside the spawn function, so self() just stand for Pid . 在第二种情况下,你可以在spawn函数之外的Pid = self() ,所以self() Pid

When you spawn/spawn_link a fun then the body of the fun is evaluated in the new process, not in the spawning process. 当您spawn/spawn_link一个fun那么的身体fun的新工艺进行评估,而不是在产卵过程。 This is what is happening in your first case, the self() call is evaluated in the new process so it does not return the value you want, the pid of the spawning process. 这就是你的第一种情况,在新进程中评估self()调用,因此它不会返回你想要的值,即产生进程的pid。 However, in your second case you first evaluate self() in the spawning process and then pass that pid into the new process, which is what you want. 但是,在第二种情况下,首先在产生过程中评估self() ,然后将该pid传递给新过程,这就是您想要的。

This is actually a common mistake. 这实际上是一个常见的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM