The main advantage of Erlang lies in multi-core programming and powerful and highly available programming.ProgramIt is inseparable from the OTP framework. The main behavior pattern gen_server in OTP, although named as a common serverCodeIt is not inherently capable of processing concurrent requests. In fact, a module written by gen_server runs in a thread, and all requests targeting it are serialized, therefore, gen_server does not have the capability of automatic parallel processing. It depends on programmers themselves to implement parallel processing. Note that gen_server: Call (or cast) is the same.
What Should programmers do on their own? We all know that the Erlang program processes are very "cheap", and you can simply process the tasks in the spawn process.
The Erlang concurrent programming template is as follows:
-Module (ctemplate ). -compile (export_all ). % start % @ spec start ()-> PID () Start ()-> % explicit MFA (module, function, argS list) enables dynamic code upgradesspawn (ctemplate, loop, [[]). % Remote Call % @ spec RPC (PID (), any ()-> Any () RPC (PID, request)-> PID! {Self (), request}, receive % PID is in the pattern match to avoid grabbing messages from all % processes... {pid, response}-> responseend. % receive loop handler % @ spec loop (any ()-> none () loop (x)-> receiveany-> IO: Format ("Received :~ P ~ N ", [any]), % tail recursion: This shocould be last call, % so it won't consume any stack spaceloop (x) end.
The concurrent processing of gen_server is to use spawn in the callback function of handle, as follows:
Handle_call (req, from, state)-> handler = state # state. store_handler, spawn (fun (req)-> res = ......, % The result gen_server: reply (from, Res) % is returned to the caller end. {noreply, State}; % is returned directly.
When using spawn, note that if you use a process dictionary to save global variables in your program, you need to use other methods.