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 20160413gcc文档确实有关于事务内存的页面,但是原语是不同的(例如,原子块是__transaction_atomic)。相反,cppreference.com上的页面似乎与N3919相关,并使用那里的原语。
如何用g++构建这些代码?
发布于 2016-08-05 10:14:16
https://stackoverflow.com/questions/38786664
复制相似问题