Template Class CThreadSafeQueue

Class Documentation

template<class T>
class CThreadSafeQueue

A thread-safe template queue for object passing between threads; for a template argument of T, the objects being passed in the queue are “T*”.

Usage example:

// Declaration:
CThreadSafeQueue<MyMsgType>  tsq;
...

// Thread 1: Write
{
  MyMsgType *msg = new MyMsgType;
  msg->...
  tsq.push(msg);  // Insert in the queue
}

// Thread 2: Read
{
  MyMsgType *msg = tsq.get();
  if (msg)
  {
     // Process "msg"...
     delete msg;
  }
}

Note that only dynamically allocated objects can be inserted with push() and that freeing that memory if responsibility of the receiver of this queue as it receives objects with get(). However, elements still in the queue upon destruction will be deleted automatically.

Public Functions

CThreadSafeQueue() = default

Default ctor.

inline virtual ~CThreadSafeQueue()
inline void clear()

Clear the queue of messages, freeing memory as required.

inline void push(T *msg)

Insert a new message in the queue - The object must be created with “new”, and do not delete is after calling this, it must be deleted later.

inline T *get()

Retrieve the next message in the queue, or nullptr if there is no message. The user MUST call “delete” with the returned object after use.

inline T *get_lastest_purge_old()

Skip all old messages in the queue and directly return the last one (the most recent, at the bottom of the queue), or nullptr if there is no message.

Note

The memory of all skipped messages is freed with “delete”.

Note

The user MUST call “delete” with the returned object after use.

inline bool empty() const

Return true if there are no messages.

inline size_t size() const

Return the number of queued messages.

Protected Attributes

std::queue<T*> m_msgs

The queue of messages. Memory is freed at destructor or by clients gathering messages.

mutable std::mutex m_csQueue

The critical section