IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

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

Erlang非业余研究 2011-10-14 13:43:00 累计浏览 2,011 次
本机暂存
    我们知道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. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. gen_tcp发送进程被挂起起因分析及对策 (累计阅读 37,821)
  2. 解析nginx负载均衡 (累计阅读 16,625)
  3. Rolling cURL: PHP并发最佳实践 (累计阅读 11,488)
  4. Facebook 网站架构 (累计阅读 11,112)
  5. 浅析C++多线程内存模型 (累计阅读 8,803)
  6. 使用Apache 和Passenger来运行puppetmaster (累计阅读 8,320)
  7. C++ 多线程编程总结 (累计阅读 8,098)
  8. LVS hash size解决4096个并发的问题 (累计阅读 6,410)
  9. 由12306.cn谈谈网站性能技术 (累计阅读 6,399)
  10. 学习:一个并发的Cache (累计阅读 6,105)