用g ++构建事务性内存C++代码

Ami*_*ory 2 c++ gcc g++ transactional-memory

cppreference网站有一个(正在进行中)页面,描述了事务性内存c ++代码.这是页面上的第一个示例

#include <iostream>
#include <vector>
#include <thread>
int f()
{
    static int i = 0;
    synchronized { // begin synchronized block
        std::cout << i << " -> ";
        ++i;       // each call to f() obtains a unique value of i
        std::cout << i << '\n';
        return i; // end synchronized block
    }
}
int main()
{
    std::vector<std::thread> v(10);
    for(auto& t: v)
        t = std::thread([]{ for(int n = 0; n < 10; ++n) f(); });
    for(auto& t: v)
        t.join();
}
Run Code Online (Sandbox Code Playgroud)

在该页面的底部,有一个迹象表明这是建立在gcc(// GCC assembly with the attribute:)之上的.

我无法在g ++ 5.3.1上构建这个:

$ g++ --std=c++11 -fgnu-tm -lpthread trx.cpp 
trx.cpp: In function ‘int f()’:
trx.cpp:7:5: error: ‘synchronized’ was not declared in this scope
     synchronized { // begin synchronized block
     ^

$ g++ --help | grep transaction

$ g++ --version
g++ (Ubuntu 5.3.1-14ubuntu2.1) 5.3.1 20160413
Run Code Online (Sandbox Code Playgroud)

gcc文档确实在事务内存上一个页面,但原语是​​不同的(例如,原子块是__transaction_atomic).相反,cppreference.com上的页面似乎与N3919相关,并使用那里的原语.

如何使用g ++构建此代码?

Bas*_*tch 5

您首先提到的transactional_memory链接说:

编译器支持

GCC从版本6.1开始支持此技术规范(需要-fgnu-tm启用).

所以你需要GCC 6(可能 -std=c++1z除了-fgnu-tm....)