1

I have a continuous loop sending packets like so from a ConcurrentQueue:

    ConcurrentQueue<packet> queue = new ConcurrentQueue<packet>();

    while(true){
        packet data;
        if (!queue.TryPeek(out packet)) continue;
        send(data);
        queue.TryDequeue(out data); //remove sent packet from the queue
    }

Each packet on a particular port has an assigned priority, (null, low, medium, high), etc.

    public struct packet
    {
        public byte[] data;
        public uint Length;
        public address addr;
        public string priority;
    }

Which algorithm could I use to send high priority packets first without blocking up the other packets in the queue?

Example:

    while(true){
        packet data;
        if (!queue.TryPeek(out packet)) continue;
        foreach(packet x in queue)
        {
            if(x.priority == "high")
            {
                send(data);
                queue.TryDequeue(out data);
            }
        }
        send(data);
        queue.TryDequeue(out data);  
    }

Example will not work as only the first packet in the queue is sent and removed. I am not sure if this is the correct approach.

Tod
  • 160
  • 12

1 Answers1

2

I think you batter use 4 different queues. One queue for each priority level. Something like:

while(true){
    packet data;
    if (highPriorityQ.TryDequeue(out data))
    {
            send(data);
            continue;
    }

    if (mediumPriorityQ.TryDequeue(out data))
    {
            send(data);
            continue;
    }

    // ...
}

Just some suggestions: Use TryDequeue directly, you could run into a deadlock between TryPeek and TryDequeue. Also, try to avoid While(true). See this question Is it safe to put TryDequeue in a while loop?

Mhd
  • 2,778
  • 5
  • 22
  • 59
  • Could you explain how to use `TryDequeue` directly? I have read the stack link provided, but I don't see what the problem would be. I check to ensure the queue is not empty with `if (highPriorityQ.IsEmpty) continue;` before `TryDequeue` should this prevent a deadlock? – Tod Aug 22 '17 at 22:15
  • I mean instead of calling `TryPeek` and after a while calling `TryDequeue`, call `TryDequeue` directly is better because even if the queue is empty `TryDequeue` will not throw exception – Mhd Aug 22 '17 at 23:18