Introduction to Erlang Concurrent programming _erlang

Source: Internet
Author: User
Tags inheritance set time

The process--process in Erlang is lightweight, and there is no sharing between processes. Looked at a lot of information, it seems that no one said that the lightweight process is what the concept, continue to find ... Gossip does not mention, into the concurrent programming world. This article is a study note, it can be said that "Concurrent programming in ERLANG," The fifth of a brief translation.

1. The creation of the process

A process is a self-contained, delimited unit of computing that runs concurrently with other processes in the system and does not have an inheritance system between processes, and of course, application developers can design such an inheritance system.
The creation of a process uses the following syntax:

Copy Code code as follows:

Pid = Spawn (Module, functionname, ArgumentList)

Spawn accepts three parameters: the module name, the function name, and the parameter list, and returns an identifier (PID) representing the created process.
If you are executing in the Pid1 of a known process:
Copy Code code as follows:

Pid2 = Spawn (Mod, Func, Args)

So, Pid2 can only be seen by PID1, the security of Erlang systems is built on limiting process expansion.

2. Inter-process communication

The communication between Erlang processes can only be achieved by sending messages, and sending messages using! Symbol:

Copy Code code as follows:

Pid! Message

Where the PID is the process tag that accepts the message. The receiver and message can be any valid Erlang structure, as long as their results return process markers and messages.
The message is accepted using the Receive keyword, and the syntax is as follows:
Copy Code code as follows:

Receive
Message1 [when Guard1]->
Actions1;
Message2 [when Guard2]->
Actions2;

End

Each Erlang process has a "mailbox" in which all messages sent to the process are stored in the "mailbox" in the order in which they are arrived, the message shown above Message1,message2, when they match the message in the mailbox and the constraint (Guard) passes, Then the corresponding Actionn is executed, and receive returns the result of the last execution statement of Actionn. Erlang is selective in the message matching in the mailbox, only the matching message will trigger the appropriate action, and no matching message will remain in the mailbox. This mechanism guarantees that no messages will block the arrival of other messages.
The order in which messages are arrived does not determine the priority of the message, and the process turns on the messages in the mailbox to try to match. The priority level of the message is explained later.

How do you accept messages for a particular process? The answer is simple, the sender (sender) also included in the message, the receiver through pattern matching to decide whether to accept, such as:

Copy Code code as follows:

Pid! {self (), ABC}

Sends message {self (), ABC} to process PID, using the self procedure to get the sender to send as a message. Then the receiving party:
Copy Code code as follows:

Receive
{pid1,msg}->

End


Pattern matching determines that only messages sent by the PID1 process are accepted.

3. Some examples
just to illustrate the process examples in the book below, I added a simple comment:

Copy Code code as follows:

-module (counter).
-compile (Export_all).
% start (), returns a new process, the process executes the loop of functions
Start ()->spawn (counter, loop,[0]).
% call this action increment count
Increment (Counter)->
Counter!increament.
% returns current Count value
Value (Counter)->
counter! {self (), value},
Receive
{counter,value}->
% return to caller
Value
End.
% Stop Count
Stop (Counter)->
counter! {self (), stop}.
Loop (Val)->
Receive
% accept different messages and decide to return the result
Increament->
Loop (val+1);
{from,value}->
from! {self (), Val},
Loop (Val);
Stop->
True
% is not above 3 kinds of messages, just continue to wait
Other->
Loop (Val)
End.


Call Mode:

Copy Code code as follows:

1> Counter1=counter:start ().
<0.30.0>
2> Counter:value (Counter1).
0
3> counter:increment (Counter1).
Increament
4> Counter:value (Counter1).
1

The process-based messaging mechanism makes it easy to implement a finite state machine (FSM), where the state uses a function representation, and the event is a message. Do not expand specifically

4. Timeout setting

The receive syntax in Erlang can add an additional option: timeout, similar to:

Copy Code code as follows:

Receive
Message1 [when Guard1]->
Actions1;
Message2 [when Guard2]->
Actions2;

After
timeoutexpr->
Actionst
End

After the timeoutexpr expression returns an integer time (millisecond level), which depends on the implementation of Erlang in the operating system or hardware. If no messages are selected within a time millisecond, the timeout setting takes effect, i.e. Actiont will execute. Time has two special values:

1 Infinity (infinity), Infinity is an atom, specifies that the timeout setting will never be executed.
2) 0, timeout if set to 0 means that the timeout setting will execute immediately, but the system will first try the message in the current "Mailbox".

Several common applications for timeouts, such as how many milliseconds to suspend the current process:

Copy Code code as follows:

Sleep (time)->
Receive
After Time->
True
End.

For example, empty the process "Mailbox", discard all messages in the "Mailbox":

Copy Code code as follows:

Flush_buffer ()->
Receive
Anymessage->
Flush_buffer ()
After 0->
True
End.

To suspend the current process forever:
Copy Code code as follows:

Suspend ()->
Receive
After
Infinity->
True
End.

Timeouts can also be applied to implementation timers, such as the following example, which creates a process that sends messages to itself after a set time:
Copy Code code as follows:

-module (timer).
-export ([TIMEOUT/2,CANCEL/1,TIMER/3]).
Timeout (time, Alarm)->
Spawn (timer, timer, [self (), Time,alarm]).
Cancel (Timer)->
The Timer! {self (), cancel}.
Timer (Pid, time, Alarm)->
Receive
{Pid,cancel}->
True
After Time->
Pid! Alarm
End.

5. Registration process
in order to send a message to a process, we need to know the PID of the process, but in some cases: there are many global servers in a large system, or the process PID needs to be hidden for security reasons. In order to achieve the purpose of sending a message to a process that does not know the PID, we provide a way to register the process and register the names of the processes, which must be atom.
Basic form of invocation:

Copy Code code as follows:

Register (Name, Pid)

To associate name with process PID
Copy Code code as follows:

Unregister (Name)

Cancels the corresponding relationship between name and the corresponding process.
Copy Code code as follows:

Whereis (Name)

Returns the PID of the process associated with name, and returns atom:undefined if no process is associated with it.
Copy Code code as follows:

Registered ()

Returns the list of names for the currently registered process

6. Priority of the process

You can use BIFs to set the priority of a process:

Copy Code code as follows:

Process_flag (priority, Pri)

The PRI can be normal, low, and the default is normal
A higher priority process will perform a little more than a relatively low level.

7. Group of processes (process group)
all Erlang processes have a PID associated with a group leader that they share, and will be added to the same process group when a new process is created. The group Leader of the original system process is itself, so it is also the group Leader of all created processes and child processes. This means that the process of Erlang is organized into a tree, where the root node is the first process created. The following bifs are used to manipulate process groups:

Group_leader ()
Returns the PID of the group leader executing the process

Group_leader (leader, Pid)
Set the process PID group leader to the leader of the process

8.Erlang process model is easy to build a client-server model , the book has a section devoted to this point, highlighting the interface design and abstraction of the isolation problem, do not translate.

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.