📜  Erlang-流程

📅  最后修改于: 2020-11-04 05:58:07             🧑  作者: Mango


Erlang中的并发粒度是一个过程。流程是与其他流程同时运行并独立于其他流程的活动/任务。 Erlang中的这些过程与大多数人熟悉的过程和线程不同。 Erlang进程是轻量级的,与其他进程(内存)隔离运行,并且由Erlang的虚拟机(VM)调度。进程的创建时间非常短,刚生成的进程的内存占用非常小,并且单个Erlang VM可以运行数百万个进程。

借助spawn方法创建一个进程。该方法的一般语法如下。

句法

spawn(Module, Name, Args)

参量

  • 模块-这是一个预定义的原子值,必须为?MODULE。

  • 名称-这是定义流程时要调用的函数的名称。

  • Args-这些是需要发送给函数。

返回值

返回创建的新流程的流程ID。

例如

以下程序显示了spawn方法的示例。

-module(helloworld). 
-export([start/0, call/2]). 

call(Arg1, Arg2) -> 
   io:format("~p ~p~n", [Arg1, Arg2]). 
start() -> 
   Pid = spawn(?MODULE, call, ["hello", "process"]), 
   io:fwrite("~p",[Pid]).

关于上述程序,需要注意以下几点。

  • 定义了一个称为call的函数,该函数将用于创建过程。

  • spawn方法使用参数hello和process调用call函数。

输出

当我们运行上面的程序时,我们将得到以下结果。

<0.29.0>"hello" "process"

现在让我们看一下进程可用的其他功能。

Sr.No. Methods & Description
1

is_pid

This method is used to determine if a process id exists.

2

is_process_alive

This is called as is_process_alive(Pid). A Pid must refer to a process at the local node.

3

pid_to_list

It converts a process id to a list.

4

registered

Returns a list with the names of all registered processes.

5

self

One of the most commonly used BIF, returns the pid of the calling processes.

6

register

This is used to register a process in the system.

7

whereis

It is called as whereis(Name). Returns the pid of the process that is registered with the name.

8

unregister

This is used to unregister a process in the system.