Muz*_*hua 3 erlang multithreading process
Erlang中的进程将调用link/1或spawn_link创建与另一个进程的链接.在我最近的一个应用程序中,我很想知道一个进程是否可以在给定的实例中知道它与其链接的其他进程的数量.这可能吗 ?他们是BIF吗?
然后,当链接进程死亡时,我想如果可以知道链接进程的数量,那么这个数字将由运行时系统自动递减.这种机制在处理Parent-ChildErlang并发程序中的关系时是理想的,即使是在不涉及的简单程序中也是如此supervisors.
那么,Erlang进程是否有out-of-the-box可能通过BIF 知道链接到它的进程数,这样每当链接进程死掉时,这个值会自动递减under-the-hood:)?
要稍微扩展一下这个问题,可以考虑一个gen_server,它将处理数千条消息handle_info.在这一部分中,它的工作就是dispatch子进程在它进入时立即处理任务.这样做的目的是确保server loop返回立即接收下一个请求.现在,子进程异步处理任务,并在它死亡之前将回复发送回请求者.在继续之前,请参阅此问题及其答案.
现在,如果,对于gen_server产生的每个子进程,都会创建一个链接,并且我想将此链接用作计数器.我知道,我知道,每个人都会像"为什么不使用gen_server State,携带说,一个计数器,然后相应地增加或减少它?":) gen_server中的某个地方,我有:
handle_info({Sender,Task},State)->
spawn_link(?MODULE,child,[Sender,Task]),
%% At this point, the number of links to the gen_server is incremented
%% by the run-time system
{noreply,State};
handle_info( _ ,State) -> {noreply,State}.
Run Code Online (Sandbox Code Playgroud)
孩子继续这样做:
child(Sender,Task)->
Result = (catch execute_task(Task)),
Sender ! Result,
ok. %% At this point the child process exits,
%% and i expect the link value to be decremented
Run Code Online (Sandbox Code Playgroud)
最后,gen_server有一个暴露的调用,如下所示:
get_no_of_links()-> gen_server:call(?MODULE,links).
handle_call(links, _ ,State)->
%% BIF to get number of instantaneous links expected here
Links = erlang:get_links(), %% This is fake, do not do it at home :)
{reply,Links,State};
handle_call(_ , _ ,State)-> {reply,ok,State}.
Run Code Online (Sandbox Code Playgroud)
现在,有人可能会问自己,真的,为什么有人想要这样做?
通常,它可以在gen_server状态中创建一个整数然后我们自己做,或者至少使gen_server handle_info类型{'EXIT',ChildPid,_Reason},然后服务器将相应地行动.我的想法是,如果有可能知道链接的数量,我会用它来知道(在给定的时刻),有多少子进程仍在忙着工作,这反过来可能实际上有助于预测服务器负载.
小智 8
来自process_info的手册:
{links,Pids}:Pids是一个pid列表,其中包含进程链接的进程
3> process_info(self(), links).
{links,[<0.26.0>]}
4> spawn_link(fun() -> timer:sleep(100000) end).
<0.38.0>
5> process_info(self(), links).
{links,[<0.26.0>,<0.38.0>]}
Run Code Online (Sandbox Code Playgroud)
我想它可以用来计算链接进程的数量
| 归档时间: |
|
| 查看次数: |
1075 次 |
| 最近记录: |