多线程安全无锁队列,求鉴定
cnlm2 2010-12-17 02:08:13 这个是基于原子操作写的, 测试环境:win32 vc2008, 代码如下,求大侠鉴定!
queue.h
#ifndef __QUEUE_H__
#define __QUEUE_H__
#include <windows.h>
template<class QElmType>
struct qnode
{
struct qnode *next;
QElmType data;
};
template<class QElmType>
class queue
{
public:
queue()
{
m_front = new qnode<QElmType>;
m_front->next = 0;
m_rear = m_front;
}
~queue() {}
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;
while (1)
{
struct qnode<QElmType> *rear = m_rear;
rear->next = p;
rear->data = e;
//如果队列没有改变将p赋值给m_rear,否则继续循环
if (InterlockedCompareExchangePointer((volatile PVOID *)&m_rear,
p, rear) == rear)
break;
}
return true;
}
bool pop(QElmType *e)
{
while (1)
{
struct qnode<QElmType> *front = m_front;
if (front == m_rear)
return false;
//如果队列位置没有变将m_front指向下一个位置,否则继续循环
if(InterlockedCompareExchangePointer((volatile PVOID *)&m_front,
m_front->next, front) == front)
{
*e = front->data;
delete front;
return true;
}
}
return true;
}
private:
struct qnode<QElmType> *m_front, *m_rear;
};
#endif //__QUEUE_H__
测试代码
testqueue.cpp
#include "queue.h"
#include <iostream>
queue<int> g_q;
DWORD WINAPI thread1(LPVOID l)
{
int i = 0;
while (1)
{
if (i%2!=0)
g_q.push(i);
i++;
Sleep(100);
}
return 0;
}
DWORD WINAPI thread2(LPVOID l)
{
int i = 0;
while (1)
{
if (i%2==0)
g_q.push(i);
i++;
Sleep(200);
}
return 0;
}
DWORD WINAPI thread3(LPVOID l)
{
int i;
while (1)
{
if (g_q.pop(&i))
std::cout << i << std::endl;
else
std::cout << "can not pop" << std::endl;
Sleep(500);
}
return 0;
}
DWORD WINAPI thread4(LPVOID l)
{
int i;
while (1)
{
if (g_q.pop(&i))
std::cout << i << std::endl;
else
std::cout << "can not pop" << std::endl;
Sleep(200);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HANDLE h1 = CreateThread(0, 0, thread1, 0, 0, 0);
HANDLE h2 = CreateThread(0, 0, thread2, 0, 0, 0);
HANDLE h3 = CreateThread(0, 0, thread3, 0, 0, 0);
HANDLE h4 = CreateThread(0, 0, thread4, 0, 0, 0);
char ch;
while (1)
{
std::cin >> ch;
if (ch == 'q')
break;
}
g_q.destroy();
return 0;
}