Erlang Program Study notes-2nd concurrent programming

Source: Internet
Author: User

http://blog.csdn.net/karl_max/article/details/3977860

1. Concurrent Primitives:

(1) Pid = spawn (fun) percent creates a new concurrent process that is used to evaluate the fun.

(2) Pid! Message percent! is the send operator, which sends the messages asynchronously, and the result is the message itself, so pid1! Pid2!...! M can send message m to multiple processes.

(3) Receive ... end percent receives a message that is sent to the current process, which is synchronous. Grammar:

Receive

PATTERN1 [When Guard1], Expressions1;

Pattern2 [When Guard1], Expressions2;

...

End

If no pattern is matched and no exception is thrown, the message is left to the next procedure to process and then waits for the following message.

2. Area_server_final.erl: A client and server that calculates the area of the program, where start () is used to encapsulate a server process that initiates a remote call (RPC), a server loop implemented with loop, As well as determining the process ID when sending and receiving messages, these methods are useful.

-module (area_server_final).

-export ([start/0, AREA/2]).

Start (), Spawn (fun loop/0).

Area (Pid, what)

RPC (Pid, what).

RPC (Pid, Request)

Pid! {self (), Request},

Receive

{Pid, Response}, Response;

End.

Loop ()

Receive

{From, {rectangle, W, H}}

From! {self (), w*h},

Loop ();

{From, {Circle, R}}

From! {self (), 3.14159*r*r};

Loop ();

{From, other}

From! {self (), {error, other}},

Loop ()

End.

Test in Erlang Shell

1> Pid = Area_server_final:start ().

2> Area_server_final:area (Pid, {rectangle, 10, 8}).

3> Area_server_final:area (Pid, {circle, 4}).

3. Erlang:system_info (process_limit). You can get the upper bound of the process allowed by the virtual machine (typically 32767), you can modify this value by +p N when starting the Erl, such as: Erl +p 500000

4. @spec statistics (Runtime), {Total CPU run time, CPU run time since last call}

@spec statistics (Wall_clock), {Total real consumption time, real time since Last call}

Real time includes the time to read and write hard drives during the run.

Note: The returned time is *1000 after the microsecond

5. The wait timeout syntax for receive:

Receive

PATTERN1 [When Guard1], Expressions1;

Pattern2 [When Guard1], Expressions2;

...

After time, percent time is milliseconds

Expressions

End

6. Custom sleep, only timeout for receive

Sleep (T)

Receive

After T

True

End.

7. The magic of receive with a timeout of 0 (can you think of any other usage?) )

(1) Clear all messages in the process mailbox:

Flush_buffer ()

Receive

_any-Flush_buffer ()

After 0

True

End.

(2) Priority to receive alarm messages, if there is a large number of messages in the mailbox, this method is inefficient (there are other methods?). )

Priority_receive ()

Receive

{Alarm, X}

{Alarm, X}

After 0

Receive

Any

End

End.

8. If the timeout value is atomic infinity, it will never time out. (What's the use of this?) Don't quite understand what the book says. )

9. Implement a timer with the receive timeout:

-module (Stimer).

-export ([START/2, CANCEL/1]).

Start (time, Fun)-spawn (Fun)-Timer (time, fun) end).

Cancel (PID)--PID! Cancel.

Timer (time, fun)

Receive

Cancel, void

After time, fun ()

End.

Working mechanism of receive (selective reception)

(1) Start a timer (in the case of after).

(2) Remove the first message from the process mailbox, make a pattern match, or delete it from the mailbox if the match is successful.

(3) If no match succeeds, put the extracted message in the "Save queue" and continue to fetch the message. Repeat this step until the match succeeds, or the mailbox is empty.

(4) If there is no successful match and the mailbox is empty at this time, the process is suspended, waiting for new messages to enter. Note that when a new message enters, only the new message is matched.

(5) If a message match succeeds, the messages in the Save queue are placed in a chronological order into the process mailbox. At this point, the timer is emptied.

(6) If the timer fires while waiting for a message, exits the wait, enters the after expression, and puts the save queue back into the process mailbox in chronological order.

11. Registration Process:

Register (Anatom, Pid). Percent percent if the atom is already registered, the call will fail.

Unregister (Anatom). Percent percent if a process has died, it will be automatically unregistered

Whereis (anatom)-Pid | Undefined

Registered (), [Anatom:atom ()] percent returns the list of all registered processes in the system.

Process-registered atoms can be used just like process PID.

12. Concurrent Program templates:

-module (ctemplate).

-compile (Export_all).

Start (), Spawn (Fun (), loop ([])).

RPC (Pid, Request)

Pid! {self (), Request},

Receive

{Pid, Response}, Response

End.

Loop (X)

Receive

Any-Io:format ("Received:~p~n", [any]),

Loop (X)

End.

13. Tail recursion Technology:

Tail recursion can be optimized as a jump command at compile time, so it can be cycled indefinitely. Tail recursion to make sure that function f does not invoke anything after invoking itself, and does not use F in the constructor of a list or tuple.

14. If you want the code to be dynamically updated at runtime, use the following spawn:

Spawn (Mod, FuncName, Args).

Where args is a parameter list of shapes such as [A1, A2, ..., an].

Explicitly indicates that the form of a module, function, and argument list is called MFA.

Erlang Program Study notes-2nd concurrent programming

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.