美文网首页
[Erlang开发之路]二十二点二、OTP练习

[Erlang开发之路]二十二点二、OTP练习

作者: 循环不计次 | 来源:发表于2019-07-24 20:04 被阅读0次

    练习简介

    本代码是个人在《Erlang程序设计》第二十二章练习题中所写的代码,书上的要求我在这里重复一下:
    通过gen_server只做一个job_center服务器(任务管理中心),任务中心持有一个必须完成的任务队列,每个任务都会被编号,任何人都可以往队列加任务,工人们可以从任务中心提取任务,并告诉任务中心自己的任务是否完成,任务用fun类型表示,要执行任务,工人必须执行fun()
    1.基本功能的接口如下:

    job_center:start_link()->true%启动任务中心服务器
    job_center:add_job(fun)->JobIndex%添加任务并返回任务序号
    job_center:work_wanted()->{JobIndex,fun}%工人们请求任务
    job_center:job_done(JobIndex)%工人们更改任务状态
    

    2.添加一个job_center:statistic()函数,报告对列内任务的完成状态
    3.添加一个监视工人的代码,如果某个工人进程挂了,要确保他的任务要重置状态
    4.检查是否有懒惰的工人,接受了工作又不按时完成工作,把请求任务的函数的返回改为{JobIndex,JobTime,fun},JobTime就是工人必须完成的时间,在JobTime-1秒的时候还没完成就发出催促消息hurry_up,在JobTime+1时还没完成就炒他犹豫exit(Pid,you_re_fired)

    我的练习代码如下:(如有错误请回复提醒我!毕竟我也是一个接触Erlang才不足10天的小菜鸟)

    在贴出我的代码前,我先说说我的思路
    1.采用ets保存任务列表,key为JobIndex,Value为fun和任务状态(done|not_done|doing)共三种
    2.如题采用gen_server来实现一套可热更新等功能的系统
    3.监控工人进程是否安的功能采用了并发编程中的monitor来监视工人进程,并spawn分裂出一个进程去receive工人进程的exit信号,当exit信号的Why是normal时,正常退出。
    4.spawn分裂出一个进程去检查懒惰的工人,用两次timer:sleep()去实现JobTime-1和JobTime+1的场景
    5.开头有一段名为DEBUG的宏定义函数。。大家就当他不存在吧。。我后面都忘记了有它的存在

    -module(job_center).
    -behaviour(gen_server).
    -export([test/0,start_link/0,job_getStatistic/1,stop/0,init/1,add_job/1,work_wanted/0,job_done/2,handle_call/3,handle_cast/2,handle_info/2,job_statistic/0]).
    -import(gen_server,[start_link/4,call/2]).
    -spec add_job(fun())->integer().
    
    -define(debug_flag,true).
    -ifdef(debug_flag).
    -define(DEBUG(X),io:format("DEBUG ~p:~p ~p~n",[?MODULE,?LINE,X])).
    -else.
    -define(DEBUG(X),void).
    -endif.
    
    test()->
            start_link(),
            job_center:add_job(fun()->good_job end).
    
    
    start_link()->
            start_link({global,?MODULE},?MODULE,[],[]).
    
    stop()->
            call(?MODULE,stop).
    
    init([])->
            State=ets:new(?MODULE,[]),
            ets:insert(State,{job_index,0}),
            {ok,State}.
    %                      user api
    add_job(Fun)->
            call(?MODULE,{add_job,Fun}).
    
    work_wanted()->
            call(?MODULE,{work_wanted}).
    
    job_done(JobNumber,Status)->
            io:format("Request change Job:~p Status:~p~n",[JobNumber,Status]),
            call(?MODULE,{job_done,JobNumber,Status}).
    
    job_statistic()->
            call(?MODULE,{job_statistic}).
    
    job_getStatistic(Index)->
            call(?MODULE,{job_getStatistic,Index}).
    
    %                    callback Function 
    handle_call({job_getStatistic,Index},_From,State)->
            {reply,ets:lookup_element(State,Index,3),State};
    handle_call({job_statistic},_From,State)->
            %未完成的任务数
            Match_not_done=ets:match(State,{'$1','$2',not_done}),
            io:format("未完成的数量:~p~n",[length(Match_not_done)]),
            Match_doing=ets:match(State,{'$1','$2',doing}),
            io:format("正在进行的数量:~p~n",[length(Match_doing)]),
            Match_done=ets:match(State,{'$1','$2',done}),
            io:format("已完成的数量:~p~n",[length(Match_done)]),
            {reply,show_all_finish,State};
    handle_call({add_job,Fun},_From,State)->
            [{job_index,Index}]=ets:lookup(State,job_index),
            ets:insert(State,[{job_index,Index+1},{Index,Fun,not_done}]),
            Reply=ok,
            {reply,Reply,State};
    
    handle_call({work_wanted},{Pid,_Ref},State)->
            Match_Ret=ets:match(State,{'$1','$2',not_done},1),
            case Match_Ret of
                '$end_of_table'->%没job了
                        Fun=void,
                        Index=-1,
                        {reply,{no_job_now,Index,Fun},State};
                 {[[Index,Fun]],_}->%判断表中还有未完成的job
                        ets:update_element(State,Index,{3,doing}),%更新状态为doing正在进行
                        %-------------------检测崩溃
                        spawn_link(fun()->
                        Ref=monitor(process,Pid),
                        receive
                                {'DOWN',Ref,process,Pid,Why}->
                                        io:format("worker:~p leave for ~p ~n",[Pid,Why]),
                                        Bool=Why=:=normal,
                                        if 
                                                Bool=:=false-> 
                                                        job_center:job_done(Index,not_done);
                                                Bool=:=true->
                                                        void
                                        end
                        end
                              end),%监控是否崩溃防止崩溃时数据停留
                        %-------------------检测超时
                        spawn(fun()->
                            timer:sleep(4000),
                            case ets:lookup_element(State,Index,3) of
                                        doing->Pid ! {hurry_up};
                                        _->ok
                            end,
                            timer:sleep(2000),
                            exit(Pid,you_are_fired)
                              end),%检测超时,超过6秒就炒鱿鱼
                        {reply,{get_job_succ,Index,Fun,5000},State}
            end;
            
    
    handle_call({job_done,JobNumber,Status},_From,State)->
            case ets:member(State,JobNumber) of%首先判断这个键值是否存在,存在才可以去lookup否则报错
                    true->
                            Status_change_before=ets:lookup_element(State,JobNumber,3),
                            %io:format("Match:~p~n",[Status_change_before]),
                            case Status_change_before of
                                    done->
                                            Reply=aleady_done;
                                    doing->
                                            Reply=good_job,
                                            io:format("comfirm to change the status:~p of Index~p~n",[Status,JobNumber]),
                                            ets:update_element(State,JobNumber,{3,Status});
                                    not_done->
                                            Reply=did_not_been_got
                            end,
                            {reply,Reply,State};
                    false->
                            {reply,job_not_found,State}
            end;
    handle_call(stop,_From,State)->
            io:format("good bye!~n"),
            {stop,normal,stopped,State}.
    
    handle_cast(_Msg,State)->
            {noreply,State}.
    
    handle_info(_Info,State)->
            {noreply,State}.
    
    terminate(_Reason,_State)->ok.
    
    code_change(_OldVsn,State,_Extra)->{ok,State}.
    
    
    

    相关文章

      网友评论

          本文标题:[Erlang开发之路]二十二点二、OTP练习

          本文链接:https://www.haomeiwen.com/subject/mqifrctx.html