views:

133

answers:

2

I'm making a thread class to use as a wrapper for pthreads. I have a Queue class to use as a queue, but I'm having trouble with it. It seems to allocate and fill the queue struct fine, but when I try to get the data from it, it Seg. faults.

http://pastebin.com/Bquqzxt0 (the printf's are for debugging, both throw seg faults)

edit: the queue is stored in a dynamically allocated "struct queueset" array as a pointer to the data and an index for the data

+3  A: 

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.

In silico
This, too, is problematic, although it's much better than the code anon posted. What if `queue.push(queueset(msg, index));` throws? (Yeah, unlikely, I know, with a `void*` and an `int`. Still.) Look here http://stackoverflow.com/questions/2842012 for a locker-type class solcing this problem.
sbi
You are correct. Edited to include a class for handling the lock for exception safety.
In silico
thanks, Im going to read up on that
anon
A: 

Your code does not show when the locks are created. Where are you using pthread_mutex_init ?

Laurent Etiemble
Somehow I missed that, my bad
anon