Erlang进程简单的主动负载管制实现

Erlang非业余研究 2011-10-14 13:43:00 累计浏览 2,154 次
    我们知道Erlang的调度器是公平的,当进程的时间片用完了后,会强制切出,但是这个粒度是比较粗的。比如说进程进行了大量的Io操作,这个操作换成时间片是不准确的,会导致某些CPU计算密集型的比较吃亏,IO密集型的合算。

    为了避免这个情况,IO密集型的经常可以互动要求短暂放弃执行,最简单的方法就是用消息等待机制。当进程在等消息的时候,就会被切出,我们就达到目的。

    我们可以参考mnesia的实现:

%%mnesia_dumper.erl:L1181
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Load regulator
%%
%% This is a poor mans substitute for a fair scheduler algorithm
%% in the Erlang emulator. The mnesia_dumper process performs many
%% costly BIF invokations and must pay for this. But since the
%% Emulator does not handle this properly we must compensate for
%% this with some form of load regulation of ourselves in order to
%% not steal all computation power in the Erlang Emulator ans make
%% other processes starve. Hopefully this is a temporary solution.                                                           

start_regulator() ->
    case mnesia_monitor:get_env(dump_log_load_regulation) of
        false ->
            nopid;
        true ->
            N = ?REGULATOR_NAME,
            case mnesia_monitor:start_proc(N, ?MODULE, regulator_init, [self()]) of
                {ok, Pid} ->
                    Pid;
                {error, Reason} ->
                    fatal("Failed to start ~n: ~p~n", [N, Reason])
            end
    end.

regulator_init(Parent) ->
    %% No need for trapping exits.
    %% Using low priority causes the regulation
    process_flag(priority, low),
    register(?REGULATOR_NAME, self()),
    proc_lib:init_ack(Parent, {ok, self()}),
    regulator_loop().

regulator_loop() ->
    receive
        {regulate, From} ->
            From ! {regulated, self()},
            regulator_loop();
        {stop, From} ->
            From ! {stopped, self()},
            exit(normal)
    end.

regulate(nopid) ->
    ok;
regulate(RegulatorPid) ->
    RegulatorPid ! {regulate, self()},
    receive
        {regulated, RegulatorPid} -> ok
    end.

    祝玩得开心!

    Post Footer automatically generated by wp-posturl plugin for wordpress.

    Post Footer automatically generated by wp-posturl plugin for wordpress.

同分类推荐文章

  1. NGINX 1.31.7: Native GeoIP2 support, HTTP/2 priorities, and QUIC improvements (2026-11-13 23:40:02)
  2. 说说广场 API 0.31.0 版的调用代码说明 (2026-11-13 19:10:02)
  3. NGINX Routing on HTTP Request Body (2026-10-27 14:10:42)

查看更多 后端 文章 →

建议继续学习

  1. gen_tcp发送进程被挂起起因分析及对策 (累计阅读 38,123)
  2. 解析nginx负载均衡 (累计阅读 17,001)
  3. Rolling cURL: PHP并发最佳实践 (累计阅读 11,970)
  4. Facebook 网站架构 (累计阅读 11,420)
  5. 浅析C++多线程内存模型 (累计阅读 9,172)
  6. 使用Apache 和Passenger来运行puppetmaster (累计阅读 8,550)
  7. C++ 多线程编程总结 (累计阅读 8,363)
  8. 由12306.cn谈谈网站性能技术 (累计阅读 6,685)
  9. LVS hash size解决4096个并发的问题 (累计阅读 6,649)
  10. 学习:一个并发的Cache (累计阅读 6,354)