Chathuri Gunawardhana
Chathuri Gunawardhana

Reputation: 171

Difference between proc_lib:spawn and rpc:call in erlang

Can you please suggest me which one is the best? In my application I need to make sure that we achieve the highest throughput.

Upvotes: 1

Views: 595

Answers (2)

Christian
Christian

Reputation: 58

Amirax pointed out the major differences. Keep in mind you could also be using rpc:async_call/4 and fetch the result later.

Ultimately: Build and measure, improve and measure again.

Upvotes: 0

Greg
Greg

Reputation: 8340

Have a look at the documentation for both, it pretty much answers your question.

  1. proc_lib:spawn_link/4

It spawns a new process on the remote node and returns pid() of the process. It also links the local process with the just spawned remote process. The new process will then call riak_kv_put_fsm:start_link/3 asynchronously, i.e. the code on the local node continues its execution and doesn't wait for the result of the call to riak_kv_put_fsm:start_link/3 on the remote node. However, if something goes wrong the remote process will crash - and because those two processes are linked, the local process will receive an 'EXIT' message from the process spawned on the remote node. See the Error Handling manual for more information about handling the 'EXIT' messages.

If everything goes OK, the execution of the process started with spawn_link will eventually end. However, whatever was the result of the call to riak_kv_put_fsm:start_link/3 will also be lost when the process stops executing. You need to have a way for the remote node to notify the local node that the call to riak_kv_put_fsm:start_link/3 has been successful and it's now ready to accept calls from the local or other nodes.

  1. rpc:call/4

It handles the call synchronously, i.e. the local process makes the call and waits until it receives a response from the remote node. If something goes wrong during the call the function will return an error. It won't crash the process until there is an error in the remote function that isn't handled properly.

Summing up, the asynchronous call with proc_lib:spawn_link/4 will be a bit slower on the remote node (because it spawns an additional process and creates the link), but it will be faster on the local node (because it doesn't need to wait for the result of the call and can continue executing). Also the synchronous call seems to be easier to comprehend, test and implement. The decision is yours.

Upvotes: 2

Related Questions