【问题标题】:Building Transactional Memory C++ Code in g++在 g++ 中构建事务性内存 C++ 代码
【发布时间】:2016-08-05 10:09:52
【问题描述】:

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,但原语不同(例如,原子块是__transaction_atomic)。相反,cppreference.com 上的页面似乎与 N3919 相关,并使用了那里的原语。

如何用 g++ 构建这段代码?

【问题讨论】:

  • 在底部它说你需要使用 gcc 6.1?
  • @Nim,哦,废话 - 错过了。非常感谢!

标签: c++ gcc g++ transactional-memory


【解决方案1】:

你首先提到的transactional_memory链接说:

编译器支持

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

所以你需要GCC 6(除了-fgnu-tm 之外,可能还有also -std=c++1z ....)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    • 2020-06-01
    相关资源
    最近更新 更多