template class mrpt::containers::CThreadSafeQueue

Overview

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.

#include <mrpt/containers/CThreadSafeQueue.h>

template <class T>
class CThreadSafeQueue
{
public:
    // construction

    CThreadSafeQueue();

    // methods

    void clear();
    void push(T* msg);
    T* get();
    T* get_lastest_purge_old();
    bool empty() const;
    size_t size() const;
};

Construction

CThreadSafeQueue()

Default ctor.

Methods

void clear()

Clear the queue of messages, freeing memory as required.

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.

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.

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.

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

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

bool empty() const

Return true if there are no messages.

size_t size() const

Return the number of queued messages.