C++ provides a built-in queue class for you:
#include <queue>
struct queueset
{
void* ptr;
int index;
queueset(void* p, int i) : ptr(p), index(i) {}
};
class pthreadmutexlock
{
public:
pthreadmutexlock()
{
pthread_mutex_init(&lock, NULL);
pthread_mutex_lock(&lock);
}
~pthreadmutexlock()
{
pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);
}
private:
pthread_mutex_t lock;
};
class ThreadSafeQueue
{
public:
void add(void* msg, int index);
queueset get();
bool hasitems() const { return !queue.empty(); }
private:
std::queue<queueset> queue;
pthread_mutex_t lock;
};
void ThreadSafeQueue::add(void* msg, int index)
{
pthreadmutexlock lock;
queue.push(queueset(msg, index));
}
queueset ThreadSafeQueue::get()
{
pthreadmutexlock lock;
queueset temp = queue.front();
queue.pop();
return temp;
}
In C++, the best way to avoid memory problems is to minimize the management of memory using raw pointers as much as possible, and use standard classes where applicable.