参考文章:
将stack class改为支持template, 并增加计数器count, 其它的基本不变
#pragma once
#include
#include
#include
#include "node.h"
template
class stack
{
public:
stack() : m_count(0) { ; }
void push(T* n);
bool pop(T*& n);
std::atomic m_count;
protected:
std::atomic head_;
};
template
void stack::push(T* n)
{
T old_head, new_head{ n };
n->n_ = nullptr;
while (!head_.compare_exchange_weak(old_head, new_head))
{
n->n_ = old_head.n_;
new_head.create_id(old_head);
}
m_count++;
}
template
bool stack::pop(T*& n)
{
T old_head, new_head;
n = nullptr;
while (!head_.compare_exchange_weak(old_head, new_head))
{
n = old_head.next_pointer();
if (!n)
break;
new_head.set(n->n_, old_head);
}
if (n != nullptr && m_count > 0) { m_count--; }
return n != nullptr;
}
主要测试stack是否为thread_local变量的比较:
A。多线程使用同一个stack
starting
2 - thread completed : 22117 nCount= 10000000 stack= 23
0 - thread completed : 22720 nCount= 10000000 stack= 16
1 - thread completed : 22803 nCount= 10000000 stack= 5
3 - thread completed : 22856 nCount= 10000000 stack= 0
no lost data
thread count : 4
target processor bits: 64
total pushes and pops: 80000000
operations per second: 3500000
processing time : 22856ms
press any key to exit
/////////////////////////////////
A。多线程使用thread_local stack
starting
1 - thread completed : 8654 nCount= 10000000 stack= 0
3 - thread completed : 8694 nCount= 10000000 stack= 0
2 - thread completed : 8710 nCount= 10000000 stack= 0
0 - thread completed : 8811 nCount= 10000000 stack= 0
no lost data
thread count : 4
target processor bits: 64
total pushes and pops: 80000000
operations per second: 9079000
processing time : 8811ms
press any key to exit
main.cpp中用thread_local 时更改
thread_local stack s;
void thread_test(std::atomic *max_elapsed, std::atomic *empty_count, size_t index)
总结:
线程中对应有自己的stack速度是最快的
说明:thread_local需要vs2015(vs2014没有测试过),新的gcc也支持。
阅读(1347) | 评论(0) | 转发(0) |