Ami Tavory Ami Tavory - 2 months ago 14x
C++ Question

Building Transactional Memory C++ Code in g++

The cppreference website has a (work in progress) page describing transactional memory c++ code. This is the first example on the page

#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)

Toward the bottom of that page, there is an indication that this builds on gcc (
// GCC assembly with the attribute:

I can't get this to build on 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 documentation does have a page on transactional memory, but the primitives are different (e.g., the atomic block is
). The page on conversely appears to be related to N3919, and uses the primitives from there.

How can this code be built with g++?


The transactional_memory link you mention first says:

Compiler support

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

So you need GCC 6 (and probably also -std=c++1z in addition to -fgnu-tm ....)