English 中文(简体)
Erlang - OTP
  • 时间:2024-09-08

Erlang - OTP


Previous Page Next Page  

OTP stands for Open Telecom Platform. It’s an apppcation operating system and a set of pbraries and procedures used for building large-scale, fault-tolerant, distributed apppcations. If you want to program your own apppcations using OTP, then the central concept that you will find very useful is the OTP behavior. A behavior encapsulates common behavioral patterns — think of it as an apppcation framework that is parameterized by a callback module.

The power of OTP comes from the properties such as fault tolerance, scalabipty, dynamic-code upgrade, and so on, can be provided by the behavior itself. So the first basic concept is to create a server component that mimics the basics of an OTP environment, let’s look at the following example for the same.

Example

-module(server). 
-export([start/2, rpc/2]). 

start(Name, Mod) -> 
   register(Name, spawn(fun() -> loop(Name, Mod, Mod:init()) end)). 
rpc(Name, Request) -> 
   Name ! {self(), Request}, 
   receive 
      {Name, Response} -> Response 
   end. 
   
loop(Name, Mod, State) ->
   receive 
      {From, Request} ->
         {Response, State1} = Mod:handle(Request, State), 
         From ! {Name, Response}, 
         loop(Name, Mod, State1) 
   end.

The following things need to be noted about the above program −

    The process if registered with the system using the register function.

    The process spawns a loop function which handles the processing.

Now let’s write a cpent program that will utipze the server program.

Example

-module(name_server). 
-export([init/0, add/2, whereis/1, handle/2]). 
-import(server1, [rpc/2]). 

add(Name, Place) -> rpc(name_server, {add, Name, Place}). 
whereis(Name) -> rpc(name_server, {whereis, Name}). 

init() -> dict:new().
handle({add, Name, Place}, Dict) -> {ok, dict:store(Name, Place, Dict)}; 
handle({whereis, Name}, Dict) -> {dict:find(Name, Dict), Dict}.

This code actually performs two tasks. It serves as a callback module that is called from the server framework code, and at the same time, it contains the interfacing routines that will be called by the cpent. The usual OTP convention is to combine both functions in the same module.

So here is how the above program needs to be run −

In erl, first run the server program by running the following command.

server(name_server,name_server)

You will get the following output −

Output

true

Then, run the following command

name_server.add(erlang,”Tutorialspoint”).

You will get the following output −

Output

Ok

Then, run the following command −

name_server.whereis(erlang).

You will get the following output −

Output

{ok,"Tutorialspoint"}
Advertisements