vendredi 28 juillet 2017

C++: When to process packets efficiently?

Short Question: What obvious mistake (misunderstanding?) am I making with the use of std::is_pointer and/or std::is_array within SafeQueue::clear()? The intent is to check for queue of pointers, then check if pointers happen to be unsigned char* or char* arrays.

This is in C++11, wrapping the std::queue class to bring something approaching thread safety.

#ifndef SAFEQUEUE_H
#define SAFEQUEUE_H

#include <queue>
#include <mutex>
#include <type_traits>

template <typename T>
class SafeQueue
{
    public:
        SafeQueue() = default; // default ctor
        SafeQueue(const SafeQueue&) = delete; // disable copy
        SafeQueue& operator=(const SafeQueue&) = delete; // disable assignment

        bool empty() const
        {
            std::unique_lock<std::mutex> ulock(m_mutex);
            return m_queue.empty();
        }

        T& front() // never called without empty() or size() > 0 check
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(!m_queue.empty()) { return m_queue.front(); }
        }

        void clear()
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(m_queue.empty()) { return; } // quick exit

            bool isPointers = (std::is_pointer<T>::value) ? true : false; // always returns true on class objects
            if(isPointers)
            {
                //bool isarray = std::is_array<T>::value ? true : false; // always returns true on class objects
                bool isarray = (std::is_same<unsigned char*, T>::value || std::is_same<char*, T>::value) ? true : false; // also returns true always
                while(!m_queue.empty())
                {
                    if(isarray) { delete[] m_queue.front(); m_queue.front() = nullptr; }
                    else { delete[] m_queue.front(); m_queue.front() = nullptr; }
                    m_queue.pop();
                }
            }
            else { std::queue<T>().swap(m_queue); }
        }

        void pop()
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            if(!m_queue.empty()) { m_queue.pop(); }
        }

        unsigned int size() const
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            return m_queue.size();
        }

        void push(const T& item)
        {
            std::unique_lock<std::mutex> lock(m_mutex);
            m_queue.push(item);
        }

    protected:
        mutable std::mutex m_mutex;
        std::queue<T> m_queue;
};

#endif // SAFEQUEUE_H

Aucun commentaire:

Enregistrer un commentaire