What happens when a gen_server method gets called simultaneously by two clients?
Asked Answered
U

4

6

I have a gen_server module that logs data to a file when a client process sends it data. What happens when two client processes send data at the same time to this module? Will the file operations conflict with each other? The erlang documentation is frustratingly unclear here.

Unconsidered answered 24/5, 2012 at 21:38 Comment(0)
C
14

Every Erlang process maintains a message queue. The process will fetch a message and handle the messages one by one.

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

But if one process has to handle too many messages from other processes, you'll need to think about the capacity of the process and optimize the design, or else it will become a bottleneck.

Carpology answered 24/5, 2012 at 22:28 Comment(1)
Thanks! I managed to find the issue. It turned out that it wasn't a concurrency problem at all (as you indicated), but rather it was a serialization problem. I wasn't using the Erlang bitstring syntax correctly to serialize my data, and so bytes were getting lost.Unconsidered
S
5

The gen_server runs in a separate process from your client process so when you do a call/cast to it you are actually sending messages to the server process.

All messages are placed in a process' message queue and processes handle their message one-by-one. If a message arrives while a process is busy then it is placed in the message queue. So log messages arriving concurrently will never interfere with each other as they will be processed sequentially.

This is not a property of the gen_server as such but a general property of all processes in erlang, which is why no mention of this is made in the gen_server documentation.

Sidedress answered 30/5, 2012 at 12:23 Comment(0)
H
0

gen_server just handles requests in the order that they was done, not matter they was done from one process or many.

In case of writing to log there is no reason to worry about race-conditions.

Hoshi answered 24/5, 2012 at 23:49 Comment(0)
S
0

Fortunately, the source for OTP is readily available at github, but the short answer is that gen_server runs in a loop, answering requests in order received, with no priority of one type (handle_cast, handle_call, or handle_info) over another.

Using handle_call can potentially be an issue, as the gen_server process will have to return before it can deal with the next cast/call/info in queue. For example, in a handle_call, avoid gen_server:call with self()!

Sladen answered 26/5, 2012 at 0:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.