What happens when the gen_server method is called simultaneously by two clients?

I have a gen_server module that logs data in a file when a client process sends data. What happens when two client processes send data simultaneously with this module? Will there be conflicting file operations with each other? erlang's documentation here is vaguely obscure.

+4
source share
4 answers

Each Erlang process supports a message queue. The process will receive the message and process the messages one by one.

In your example, if two clients call gen_server at the same time, these calls will become a message in the queue of the gen_server process, and gen_server will process these messages one by one. Therefore, no need to worry about conflict.

But if one process needs to process too many messages from other processes, you need to think about the capacity of the process and optimize the design, otherwise it will become a bottleneck.

+13
source

Gen_server is started by a separate process from your client process, so when you make a call / drop it, you actually send messages to the server process. All messages are placed in the process message queue, and processes process their message one by one. If a message arrives when the process is busy, it is placed in the message queue. Thus, log messages arriving simultaneously will never interfere with each other, as they will be processed sequentially.

This is not a gen_server property per se, but a common property of all processes in erlang, so this is not mentioned in the gen_server documentation.

+5
source

gen_server simply processes requests in the order in which they were executed, no matter what they were made from one process or many.

With a journal entry, there is no reason to worry about racial conditions.

0
source

Fortunately, the OTP source is easily accessible on github , but the short answer is that gen_server runs in a loop, responding to requests in the order received, without priority of one type (handle_cast, handle_call or handle_info) over the other.

Using handle_call could potentially be a problem, since the gen_server process will have to return before it can handle the next cast / call / information queue in the queue. For example, in handle_call, avoid gen_server: call with self ()!

0
source

Source: https://habr.com/ru/post/1414261/


All Articles