參考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.