- 论坛徽章:
- 0
|
不好意思 可能我上面没有说清楚
我用的是下面这个环形队列 无锁的实现一个进程读,一个进程写,没有牵涉到其他线程。
这样的方式把10个线程串成一条流水线,主线程把指针push到第一个线程的环形队列,第一个线程从环形队列里面pop出来一个数据(指针),然后处理(不会修改这个指针指向的值),然后把这个指针插入到下一个线程的队列,下一个线程也从自己的队列里面pop一个数据,然后处理,再push到下下个线程的队列。
所以只有一个线程的队列满了,push不进去会循环的push,知道能够push进去,或者是队列空了,pop出来的数据null,会继续pop,这两种情况下会忙等,不然是不会忙等的,而这两种情况在测试的时候很少发生,对性能影响应该很小。- template<class T>
- class RingQueue {
- public:
- RingQueue() {
- cout << "RingQueue::ctor" << endl;
- };
- virtual ~RingQueue() {
- cout << "RingQueue::destory" << endl;
- };
- void InitQueue() {
- Push_Count = 0;
- Push_Index = 0;
- Pop_Count = 0;
- Pop_Index = 0;
- memset(List, 0, sizeof (List));
- }
- bool Push(const T& AData) {
- if (Push_Count - Pop_Count < Max_Count) {
- List[Push_Index] = AData;
- Push_Count++;
- if (Push_Index == High_Index)
- Push_Index = 0;
- else
- Push_Index++;
- return true;
- } else
- return false;
- }
- T Pop() {
- T result = NULL;
- if (Push_Count != Pop_Count) {
- result = List[Pop_Index];
- Pop_Count++;
- if (Pop_Index == High_Index)
- Pop_Index = 0;
- else
- Pop_Index++;
- }
- return result;
- }
- long size() {
- return this->Push_Count - this->Pop_Count;
- }
- private:
- RingQueue(const RingQueue& orig);
- T List[524288 * 2]; //2^19 4M�ռ�
- const static unsigned long Max_Count = 524288 * 2;
- const static unsigned long High_Index = 524288 * 2 - 1;
- unsigned long Push_Count;
- unsigned long Push_Index;
- unsigned long Pop_Count;
- unsigned long Pop_Index;
- };
复制代码 |
|