-module(allocator).
-export([start/1,server/2,allocate/0,free/1]).//外部只看到这个模块的这四个函数
//管理两个列表,Free/Allocated
start(Resources) ->
Pid = spawn(allocator, server, [Resources,[]]), //Resources为系统提供的free资源,allocated为空。
register(resource_alloc, Pid). //resource_alloc是Pid的别名,下面所有的resource_alloc都指向这个进程
% The interface functions.
allocate() ->
request(alloc).
free(Resource) ->
request({free,Resource}).
request(Request) ->
resource_alloc ! {self(),Request},//向Pid发送请求
receive //等候发送请求的响应
{resource_alloc,Reply} ->
Reply
end.
% The server.接收分配和释放的请求服务,接收到一个请求即返回
server(Free, Allocated) ->
receive
{From,alloc} ->
allocate(Free, Allocated, From);
{From,{Free,R}} ->
free(Free, Allocated, From, R)
end.
allocate([R|Free], Allocated, From) ->
From ! {resource_alloc,{yes,R}},
server(Free, [{R,From}|Allocated]); //将{R,From}插入Allocated,继续等待请求
allocate([], Allocated, From) ->
From ! {resource_alloc,no},
server([], Allocated).//继续等待请求
free(Free, Allocated, From, R) ->
case lists:member({R,From}, Allocated) of //检查{R.From}是否在Allocated中
true ->
From ! {resource_alloc,ok},
server([R|Free], lists:delete({R,From}, Allocated));
false ->
From ! {resource_alloc,error},
server(Free, Allocated)
end.
erlang:一个简单的资源分配器
这段代码实现了一个用Erlang编写的资源分配器,它维护了两个列表来跟踪可用(Free)和已分配(Allocated)的资源。通过`start`函数启动,使用`allocate`和`free`接口进行资源的申请和释放。内部的`server`进程处理这些请求,确保资源的正确分配和释放。该设计允许并发操作,适合于高并发的分布式系统。
摘要由CSDN通过智能技术生成