gpt4 book ai didi

concurrency - 在 Erlang 中发送/接收消息(并发)

转载 作者:行者123 更新时间:2023-12-02 18:54:17 27 4
gpt4 key购买 nike

我正在尝试解决以下问题:

Write an Erlang function named respond that takes two parameters, a process ID named Pid and an Erlang item named Item. The function should send a message to Pid; the message should be a tuple with two elements: respond’s process ID and Item. Then, the function should wait to receive a message back. If the message it receives is true, then print “That is correct!” If the message it receives is false, then print “That is incorrect!” If the message it receives is an error, then print “There was an error in the input.” If the message is anything else, then print “Invalid message received.”

我写了以下内容:

respond(Pid,Item) ->
Pid ! {Pid,Item};
receive
true -> io:format(~p~n "That is correct",[]);
false -> io:format(~p~n "That is incorrect",[]);
error -> io:format(~p~n "There was an error in the input",[]);
_ -> io:format(~p~n "Invalid message received",[])
end.

编译代码时遇到的错误如下:

1> c(main).
main.erl:15: syntax error before: 'receive'
main.erl:2: function respond/2 undefined
error

是什么导致了这个错误?我对这个问题的解决方法是否正确?

最佳答案

你们真的非常接近。

问题在于 Erlang 中的表达式不是由 ; 分隔的。它们由 , 分隔。

尝试...

respond(Pid,Item) ->
Pid ! {Pid,Item},

还有……一个小提示:响应的进程 ID 不是 Pid。要获取响应的进程 ID,您应该使用 self/0 .

关于concurrency - 在 Erlang 中发送/接收消息(并发),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66383303/

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