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++ 构建此代码?

最佳答案

您首先提到的 transactional_memory 链接说:

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

关于c++ - 用 g++ 构建事务性内存 C++ 代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38786664/

10-13 08:51
查看更多