Erlang concurrent programming Template

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.