一读一写无锁队列c++实现

来源:互联网 发布:淘宝店主在哪里进货 编辑:程序博客网 时间:2024/06/06 19:48

限制一个线程读,一个线程写,不加锁的队列,使用单链表实现,测试环境:centos 5.9 


[root@localhost test]# cat  test.cpp    

#include <iostream>#include <pthread.h>template<class QElmType>struct qnode{    struct qnode *next;    QElmType data;};template<class QElmType>class queue{public:        queue() {init();}        ~queue() {destroy();}        bool init()        {                m_front = m_rear = new qnode<QElmType>;                if (!m_front)                        return false;                m_front->next = 0;                return true;        }        void destroy()        {                while (m_front)                {                        m_rear = m_front->next;                        delete m_front;                        m_front = m_rear;                }        }        bool push(QElmType e)        {                struct qnode<QElmType> *p = new qnode<QElmType>;                if (!p)                        return false;                p->next = 0;                m_rear->next = p;                m_rear->data = e;                m_rear = p;                return true;        }        bool pop(QElmType *e)        {                if (m_front == m_rear)                        return false;                struct qnode<QElmType> *p = m_front;                *e = p->data;                m_front = p->next;                delete p;                return true;        }private:  struct qnode<QElmType> * volatile m_front, * volatile m_rear;};queue<int> g_q;void *thread1(void * l){        int i = 0;        while (1)        {                g_q.push(i);                i++;                usleep(::rand()%1000);        }        return 0;}void *thread2(void * l){        int i;        while (1)        {                if (g_q.pop(&i))                        std::cout << i << std::endl;                //else                        //std::cout << "can not pop" << std::endl;                usleep(::rand()%1000);        }        return 0;}int main(int argc, char* argv[]){        pthread_t t1,t2;        pthread_create(&t1, 0, thread1, 0);        pthread_create(&t2, 0, thread2, 0);        char ch;        while (1)        {                std::cin >> ch;                if (ch == 'q')                        break;        }       return 0;}


代码比较简单,只实现2个线程间的无锁。

这个无锁队列主要是使用两个volatile 的指针来判断是否还有任务( volatile m_front, * volatile m_rear)。

只能实现两个线程间的无锁队列,一个是工作者线程一个是提供任务线程,因为不能让两个或以上的线程来修改指针m_front 和指针m_rear,否者会出现问题。

这个无锁队列的实现是基于m_front指针的修改是由一个线程来完成的,m_rear的修改是由另一个线程来完成的,不会出现同时两个线程修改同一个指针。




原创粉丝点击