在 g++ 中构建事务内存 C++ 代码

Building Transactional Memory C++ Code in g++

cppreference 网站有一个 (work in progress) page describing transactional memory c++ code。这是页面上的第一个示例

#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();
}

在该页面的底部,有迹象表明这是基于 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

gcc 文档 a page on transactional memory, but the primitives are different (e.g., the atomic block is __transaction_atomic). The page on cppreference.com conversely appears to be related to N3919,并使用那里的原语。

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

你先提到的transactional_memorylink说:

Compiler support

This technical specification is supported by GCC as of version 6.1 (requires -fgnu-tm to enable).

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