C++20 Transaction Memory

Transaction Memory is a concurrency mechanism, which provides atomic and isolated compared with normal memory access. Transaction memory is easy to use, and simplify concurrent programming without lock or extra concurrent control method.

C++20 implements Transaction Memory, and makes this becomes a standard in C++. I think this is the inevitable trend with rapid development in multi-core programming.

In gcc-7, programmer can use more than three ways to use Transaction Memory, and I will introduce how to write codes by taking advantage of Transaction Memory

Below is a example with using synchronized keyword to achieve synchronized of multi threads.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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();
}

The output in screen is like that:

1
2
3
4
0 -> 1
1 -> 2
...
99 -> 100

Only one thread can access this variable i at any time.