TSX指令集之RTM无锁并发能加快速度吗?与mutex加锁比较

下面是实验代码和截图。

  • 需要确保自己的服务器CPU能支持RTM指令集,如何查看能否支持RTM指令集不做介绍
  • 编译指令:g++ test4.cc -std=c++11 -pthread -mrtm
  • -mrtm表示使用rtm指令集,需要导入头文件#include <immintrin.h>
#include <immintrin.h>
#include <sys/time.h>

#include <iostream>
#include <thread>
#include <vector>
#include <mutex>

using namespace std;


int a1 = 0; // 使用无锁,无RTM来累加a1,结果肯定出错
int a2 = 0; // 设置mutex来累加a2,结果不会出错
int a3 = 0; // 使用RTM来累加a3,结果不会出错
mutex mtx;

void func1() {
	for (int i = 0; i < 100000; i++) a1++;

}
void func2() {
	mtx.lock();
	for (int i = 0; i < 100000; i++) a2++;
	mtx.unlock();
}

void func3() {
    while (_xbegin() != _XBEGIN_STARTED) {}
    for (int i = 0; i < 100000; i++) a3++;
    _xend();
}

int main() {

	struct timeval _start_tv, _end_tv;
    long long total_us;
        
    /*****************************************************************************/
    vector<thread> threads1;
	threads1.reserve(static_cast<size_t>(10));
    gettimeofday (&_start_tv, NULL);
	for (int i = 0; i < 10; ++i) {
		threads1.emplace_back(func1);
	}
    for (auto &t : threads1) {
		t.join();
	}
    gettimeofday (&_end_tv, NULL);
    total_us = (_end_tv.tv_sec - _start_tv.tv_sec) * 1000000 + (_end_tv.tv_usec - _start_tv.tv_usec);
	
    cout << "无锁,无RTM:"<< endl;
	cout << "a1 = " << a1 << endl;
    cout << "time = " << total_us << " 微秒" << endl << endl;

    /*****************************************************************************/

    vector<thread> threads2;
	threads2.reserve(static_cast<size_t>(10));
    gettimeofday (&_start_tv, NULL);
	for (int i = 0; i < 10; ++i) {
		threads2.emplace_back(func2);
	}
    for (auto &t : threads2) {
		t.join();
	}
    gettimeofday (&_end_tv, NULL);
    total_us = (_end_tv.tv_sec - _start_tv.tv_sec) * 1000000 + (_end_tv.tv_usec - _start_tv.tv_usec);
	
    cout << "使用mutex锁: "<< endl;
	cout << "a2 = " << a2 << endl;
    cout << "time = " << total_us << " 微秒" << endl << endl;


    /*****************************************************************************/
    vector<thread> threads3;
	threads3.reserve(static_cast<size_t>(10));
    gettimeofday (&_start_tv, NULL);
	for (int i = 0; i < 10; ++i) {
		threads3.emplace_back(func3);
	}
    for (auto &t : threads3) {
		t.join();
	}
    gettimeofday (&_end_tv, NULL);
    total_us = (_end_tv.tv_sec - _start_tv.tv_sec) * 1000000 + (_end_tv.tv_usec - _start_tv.tv_usec);
	
    cout << "使用RTM 事务内存: "<< endl;
	cout << "a3 = " << a3 << endl;
    cout << "time = " << total_us << " 微秒" << endl << endl;


}

// g++ test4.cc -std=c++11 -pthread -mrtm

输出如下:
在这里插入图片描述
如果加大a3的累加数量,RTM事务内存可能很长一段时间无法输出结果。

到底RTM指令集如何才能达到最佳使用效果,还请后来人研究。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值