- RTM 功能的头文件可以引入#include
- 以下文件编译指令g++ test.cc -pthread -std=c++11 -mrtm
- 前提是你的服务器支持RTM指令集,通过cat /proc/cpuinfo查看flags一项中是否包含rtm即可:cat /proc/cpuinfo | grep rtm
- 下面的程序的输出结果为100000,因为有10个线程,每个线程在a上面累加10000,输出结果为10000,符合预期。
- RTM指令集包括4个函数:_xbegin(),_xend(),_xabort(),_xtest();
- intel指令集手册官网可查RTM详细说明:intel RTM 指令集手册
#include
#include
#include
#include
using namespace std;
int a = 0;
void func() {
while (_xbegin() != _XBEGIN_STARTED) {}
for (int i = 0; i < 10000; i++) a++;
_xend();
}
int main() {
vector threads;
threads.reserve(static_cast(10)); // 预留10个线程大小的空间
for (int i = 0; i < 10; ++i) { // 创建10个线程
threads.emplace_back(func);
}
for (auto &t : threads) {
t.join();
}
cout << "a = " << a << endl;
return 0;
}