如何使循环队列成为线程安全的?

时间:2013-04-01 20:36:38

标签: c++ multithreading queue

所以我的Enqueue和Dequeue功能如下。我如何采取我所拥有的并使其线程安全?我考虑过使用Windows.h中的互斥锁,但是如果可能的话,我不想将我的程序限制为仅限Windows。

void Queue::Enqueue(int num){
    //increase recorded size
    size++;
    //stick in num
    numbers[nextSpace] = num;
    //find the next available space
    nextSpace = (++nextSpace) % maxSize;
}

int Queue::Dequeue(){
    int temp;
    temp = items[curSpace];
    curSpace = (++curSpace) % maxSize;
    size--;
    return temp;
}

1 个答案:

答案 0 :(得分:0)

您可以参考此代码(使用pthreads):

#include<pthread.h> 
#define DEFAULT_SIZE 100
class circularQueue{
 private:
    int *m_queue;
    int p_head;
    int p_tail;
    int m_cap;
    pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER; 
    public:
        circularQueue(int size)
        {
            /*in case invalid input*/
            if(size<0)
                size = DEFAULT_SIZE ;

            m_queue = new int[size];
            p_head = 0;
            p_tail = -1;
            m_cap = 0;
            pthread_mutex_init(&mp,NULL);
        }

        bool enqueue(int x)
        {
            bool res= false;
            p_thread_mutex_lock(&mp);
            /*queue is full*/
            if(m_cap == size)
            {
                res = false;
            }
            else
            {
                m_queue[(++p_tail)%size)] = x;
                ++m_cap;
                res = true;
            }
            p_thread_mutex_unlock(&mp);
            return res;
        }
        int dequeue()
        {
            int res=0;

            pthread_mutex_lock(&mp);
            /*empty queue*/
            if(m_cap == 0)
            {    
                throw("empty queue!");
                pthread_mutex_unlock(&mp);
            }
            else{
                res = m_queue[p_head];    
                p_head = (p_head+1)%size;
            }
            pthread_mutex_unlock(&mp);
            return res;
        }    
        ~virtual circularQueue()
        {
            delete[] m_queue;
            m_queue = NULL;
            pthread_mutex_destroy(&mp);
        }
}