Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2647334
  • 博文数量: 416
  • 博客积分: 10220
  • 博客等级: 上将
  • 技术积分: 4193
  • 用 户 组: 普通用户
  • 注册时间: 2006-12-15 09:47
文章分类

全部博文(416)

文章存档

2022年(1)

2021年(1)

2020年(1)

2019年(5)

2018年(7)

2017年(6)

2016年(7)

2015年(11)

2014年(1)

2012年(5)

2011年(7)

2010年(35)

2009年(64)

2008年(48)

2007年(177)

2006年(40)

我的朋友

分类: C/C++

2015-02-08 11:25:23

参考文章:

将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也支持。
阅读(1270) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~