问题描述
我正在尝试构建一个非常简单的屏障同步服务器,该服务器最初会被喂以许多与之通信的进程.进程完成后,它将收到带有该进程的Pid的消息,并保留要执行此操作的每个进程的列表.当屏障达到零(所有进程都已发送消息)时,我的服务器需要向其中每个发送一条消息(我使用 [Pid | ProcList]
作为我的pids列表).
I am trying to build a very simple barrier-synchronization server, where the server is initially fed a number of processes that will be communicating with it. When a process is done, it receives a message with that process' Pid, and it keeps a list of every process to do so. When the barrier reaches zero (all processes have sent messages), my server needs to send a message to each of these (I am using [Pid | ProcList]
as my list of pids).
我尝试使用辅助函数无济于事,列表理解使我陷入无限循环,因此我正在研究如何使用list:foreach来解决这一问题.我对函数式编程相当陌生,但是据我了解,此foreach需要接收列表以及lambda微积分函数,以将消息发送到列表中的每个节点.由于!"的中缀性质,我尚未找到一种在不引起语法错误的情况下进行此操作的方法.
I have tried using a helper function to no avail, list comprehensions keep me in an infinite loop, and as such I am looking into how to use lists:foreach to take care of this.I am fairly new to functional programming, but from what I understand, this foreach needs to take in the list as well as a lambda-calculus function to send a message to each node in the list. Due to the infix nature of "!", I have yet to find a way to do this without causing syntax errors.
推荐答案
如何在列表理解中实现无限循环?我必须说,这非常具有挑战性.试试这个:
How you've made infinite loop in list comprehension? I must say, that's quite challenging. Try this:
Message = % broadcast message goes here
ListOfPids = % list of recipients
[Pid ! Message || Pid <- ListOfPids].
如果要使用 foreach
,则它将一个参数函数作为第一个参数,因此需要先包装 send
,因为它是两个参数函数.
If you want to use foreach
, than it takes one argument function as first argument, so need to wrap send
first, as it is two argument function.
Message = % broadcast message goes here
ListOfPids = % list of recipients
Fun = fun (Pid) -> Pid ! Message end,
lists:foreach(Fun, ListOfPids).
这篇关于在Erlang中,将消息传递到pid列表的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!