Search code examples
c#queueqos

Basic QoS Algorithm?


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.


Solution

  • 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?