下面是实验代码和截图。
- 需要确保自己的服务器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指令集如何才能达到最佳使用效果,还请后来人研究。