首页 > 其他 > 详细

Rabbitmq中的优先级队列操作

时间:2014-08-31 23:08:32      阅读:675      评论:0      收藏:0      [点我收藏+]

1、%% 普通队列操作
in(X, 0, {queue, [_] = In, [], 1}) ->{queue, [X], In, 2};
in(X, 0, {queue, In, Out, Len}) when is_list(In), is_list(Out) -> {queue, [X|In], Out, Len + 1};

优先级队列操作:
in(X, Priority, Q = {queue, [], [], 0}) -> in(X, Priority, {pqueue, []});
in(X, Priority, Q = {queue,
, , }) -> in(X, Priority, {pqueue, [{0, Q}]});

主要的操作:

in(X, Priority, {pqueue, Queues}) ->
P = maybe_negate_priority(Priority),
{pqueue, case lists:keysearch(P, 1, Queues) of
             {value, {_, Q}} ->
                 lists:keyreplace(P, 1, Queues, {P, in(X, Q)});
             false when P == infinity ->
                 [{P, {queue, [X], [], 1}} | Queues];
             false ->
                 case Queues of
                     [{infinity, InfQueue} | Queues1] ->
                         [{infinity, InfQueue} |
                          lists:keysort(1, [{P, {queue, [X], [], 1}} | Queues1])];
                     _ ->
                         lists:keysort(1, [{P, {queue, [X], [], 1}} | Queues])
                 end
         end}.

根据优先级队列的优先级进行排序操作,如果队列的优先级为infinity则放在头部,其它队列优先级按照优先级数排序

2、%%出对列操作,其中 如果出队列后出队列为空,则从入队列中取出r2f(In,Len-1)到出队列当中
out({queue, [], [], 0} = Q) ->{empty, Q};
out({queue, [V], [], 1}) ->{{value, V}, {queue, [], [], 0}};
out({queue, [Y|In], [], Len}) ->

[V|Out] = lists:reverse(In, []),
{{value, V}, {queue, [Y], Out}, Len - 1};

out({queue, In, [V], Len}) when is_list(In) -> {{value,V}, r2f(In, Len - 1)};
out({queue, In,[V|Out], Len}) when is_list(In) -> {{value, V}, {queue, In, Out, L - en1}};

出队列的关键步骤:

out({pqueue, [{P, Q} | Queues]}) ->
{R, Q1} = out(Q),
NewQ = case is_empty(Q1) of
           true -> case Queues of
                       []           -> {queue, [], [], 0};
                       [{0, OnlyQ}] -> OnlyQ;
                       [_|_]        -> {pqueue, Queues}
                   end;
           false -> {pqueue, [{P, Q1} | Queues]}
       end,
{R, NewQ}.

有优先级的队列,则取出优先级后,Q队列如果为空,判断下个队列Queues,否则返回 {pqueue, [{P, Q1} | Queues]}

总结:入队和出队操作相对应,只是出队列操作返回的数格式不一样,类似 {{value, V}, {queue, In, Out, L - en1}}

Rabbitmq中的优先级队列操作

原文:http://my.oschina.net/u/932809/blog/308542

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!