erlang:hibernate/3函数的使用案例

参考rabbitmq代码的使用状况:函数

mainloop1(Deb, State = #wstate{pending = []}) ->
    receive
        Message -> {Deb1, State1} = handle_message(Deb, Message, State),
                   ?MODULE:mainloop1(Deb1, State1)
    after ?HIBERNATE_AFTER ->
            erlang:hibernate(?MODULE, mainloop, [Deb, State])
    end;
mainloop1(Deb, State) ->
    receive
        Message -> {Deb1, State1} = handle_message(Deb, Message, State),
                   ?MODULE:mainloop1(Deb1, State1)
    after 0 ->
            ?MODULE:mainloop1(Deb, internal_flush(State))
    end.

就是使用进程递归的函数,而后进程的状态值给填进参数里面。oop

gen_server、gen_fsm等模块都使用了hibernate特性,就是返回状态的最后的Timeout值能够使用hibernate.这样一些好久不活跃的进程,可让它睡眠,回收使用的内存。但要注意,这个函数会执行2次内存回收,若是进程很频繁切换,这样反而会影响性能。性能

gen_fsm文档里面写道:this

The gen_fsm process can go into hibernation (see erlang:hibernate/3) 
if a callback function specifies 'hibernate' instead of a time-out value. 
This can be useful if the server is expected to be idle for a long time.
 However, use this feature with care, as hibernation implies at least two garbage collections
 (when hibernating and shortly after waking up) and is not something
 you want to do between each call to a busy state machine.
相关文章
相关标签/搜索