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

Building Transactional Memory C++ Code in g++

本文关键字:内存 C++ 代码 事务 构建 g++      更新时间:2023-10-16

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

在该页面的底部,有一个迹象表明这是建立在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文档在事务内存上有一个页面,但基元不同(例如,原子块是__transaction_atomic(。相反,cppreference.com上的页面似乎与N3919有关,并使用那里的基元。

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

您首先提到的transactional_memory链接显示:

编译器支持

GCC从6.1版起支持本技术规范(需要启用-fgnu-tm(。

因此,您需要GCC 6(可能除了-fgnu-tm之外还有-std=c++1z……(