命名空间
变体
操作

事务性内存 (TM TS)

来自 cppreference.cn
< cpp‎ | 语言
 
 
C++ 语言
 
 

事务性内存是一种并发同步机制,它将语句组合并到事务中,这些事务具有以下特性:

  • 原子性(所有语句要么全部发生,要么全部不发生)
  • 隔离性(事务中的语句不能观察到另一个事务的半写入,即使它们并行执行)

典型的实现会在支持硬件事务性内存的范围内(例如,直到变更集饱和)使用它,并回退到软件事务性内存,通常通过乐观并发实现:如果另一个事务更新了事务使用的一些变量,则会静默重试。因此,可重试事务(“原子块”)只能调用事务安全函数。

请注意,在事务内部和外部访问变量而没有其他外部同步会导致数据竞争。

如果支持特性测试,此处描述的特性由宏常量 __cpp_transactional_memory 表示,其值等于或大于 201505

目录

[编辑] 同步块

synchronized 复合语句

复合语句作为在全局锁下执行:程序中所有最外层的同步块以单个总顺序执行。每个同步块的结束与该顺序中下一个同步块的开始同步。嵌套在其他同步块中的同步块没有特殊语义。

同步块不是事务(与下面的原子块不同),并且可以调用事务不安全函数。

#include <iostream>
#include <thread>
#include <vector>
 
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();
}

输出

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

通过任何方式(到达末尾、执行 goto、break、continue 或 return,或抛出异常)离开同步块会退出该块,如果退出的块是最外层块,则与单个总顺序中的下一个块同步。如果使用 std::longjmp 退出同步块,则行为未定义。

不允许通过 goto 或 switch 进入同步块。

尽管同步块执行时如同在全局锁下,但期望的实现会检查每个块内的代码,并对事务安全代码使用乐观并发(在可用时由硬件事务性内存支持),对非事务安全代码使用最小锁定。当同步块调用非内联函数时,编译器可能必须退出推测性执行并在整个调用周围持有锁,除非该函数声明为 transaction_safe(见下文)或使用了属性 [[optimize_for_synchronized]](见下文)。

[编辑] 原子块

atomic_noexcept 复合语句

atomic_cancel 复合语句

atomic_commit 复合语句

1) 如果抛出异常,则调用 std::abort
2) 如果抛出异常,则调用 std::abort,除非该异常是用于事务取消的异常之一(见下文),在这种情况下,事务被*取消*:程序中所有被原子块操作的副作用修改的内存位置的值都会恢复到原子块执行开始时的值,并且异常照常继续栈展开。
3) 如果抛出异常,事务正常提交。

atomic_cancel 块中用于事务取消的异常是 std::bad_allocstd::bad_array_new_lengthstd::bad_caststd::bad_typeidstd::bad_exceptionstd::exception 及其所有标准库派生异常,以及特殊异常类型 std::tx_exception<T>

原子块中的 复合语句 不允许执行任何非 transaction_safe 的表达式、语句或调用任何非 transaction_safe 的函数(这是编译时错误)。

// each call to f() retrieves a unique value of i, even when done in parallel
int f()
{
    static int i = 0;
    atomic_noexcept { // begin transaction
//  printf("before %d\n", i); // error: cannot call a non transaction-safe function
        ++i;
        return i; // commit transaction
    }
}

通过异常以外的任何方式(到达末尾、goto、break、continue、return)离开原子块都会提交事务。如果使用 std::longjmp 退出原子块,则行为未定义。

[编辑] 事务安全函数

函数可以通过在其声明中使用关键字 transaction_safe 显式声明为事务安全。

lambda 声明中,它出现在捕获列表之后,或紧随(关键字 mutable 之后(如果使用了)。

extern volatile int * p = 0;
struct S
{
    virtual ~S();
};
int f() transaction_safe
{
    int x = 0;  // ok: not volatile
    p = &x;     // ok: the pointer is not volatile
    int i = *p; // error: read through volatile glvalue
    S s;        // error: invocation of unsafe destructor
}
int f(int x) { // implicitly transaction-safe
    if (x <= 0)
        return 0;
    return x + f(x - 1);
}

如果通过指向事务安全函数的引用或指针调用非事务安全函数,则行为未定义。


指向事务安全函数的指针和指向事务安全成员函数的指针分别隐式转换为指向函数和指向成员函数的指针。结果指针是否与原始指针相等是未指定的。

[编辑] 事务安全虚函数

如果 transaction_safe_dynamic 函数的最终覆盖器未声明为 transaction_safe,则在原子块中调用它是未定义行为。

[编辑] 标准库

除了引入新的异常模板 std::tx_exception 外,事务性内存技术规范对标准库进行了以下更改:

  • 使以下函数显式地为 transaction_safe
  • 使以下函数显式地为 transaction_safe_dynamic
  • 所有支持事务取消的异常类型(见上述 atomic_cancel)的每个虚成员函数
  • 要求在 Allocator X 上事务安全的所有操作在 X::rebind<>::other 上也是事务安全的。

[编辑] 属性

属性 [[optimize_for_synchronized]] 可以应用于函数声明中的声明符,并且必须出现在函数的第一个声明上。

如果在某个翻译单元中函数声明为 [[optimize_for_synchronized]],而在另一个翻译单元中函数未声明为 [[optimize_for_synchronized]],则程序格式错误;无需诊断。

它表明函数定义应该针对从 synchronized 语句的调用进行优化。特别是,它避免了序列化调用对大多数调用事务安全但并非所有调用都事务安全(例如,可能需要重新哈希的哈希表插入,可能需要请求新块的分配器,可能很少记录的简单函数)的函数的同步块。

std::atomic<bool> rehash{false};
 
// maintenance thread runs this loop
void maintenance_thread(void*)
{
    while (!shutdown)
    {
        synchronized
        {
            if (rehash)
            {
                hash.rehash();
                rehash = false;
            }
        }
    }
}
 
// worker threads execute hundreds of thousands of calls to this function 
// every second. Calls to insert_key() from synchronized blocks in other
// translation units will cause those blocks to serialize, unless insert_key()
// is marked [[optimize_for_synchronized]]
[[optimize_for_synchronized]] void insert_key(char* key, char* value)
{
    bool concern = hash.insert(key, value);
    if (concern)
        rehash = true;
}

没有属性的 GCC 汇编:整个函数被序列化

insert_key(char*, char*):
	subq	$8, %rsp
	movq	%rsi, %rdx
	movq	%rdi, %rsi
	movl	$hash, %edi
	call	Hash::insert(char*, char*)
	testb	%al, %al
	je	.L20
	movb	$1, rehash(%rip)
	mfence
.L20:
	addq	$8, %rsp
	ret

有属性的 GCC 汇编

transaction clone for insert_key(char*, char*):
	subq	$8, %rsp
	movq	%rsi, %rdx
	movq	%rdi, %rsi
	movl	$hash, %edi
	call	transaction clone for Hash::insert(char*, char*)
	testb	%al, %al
	je	.L27
	xorl	%edi, %edi
	call	_ITM_changeTransactionMode # Note: this is the serialization point
	movb	$1, rehash(%rip)
	mfence
.L27:
	addq	$8, %rsp
	ret

[编辑] 注释

[编辑] 关键字

atomic_cancel, atomic_commit, atomic_noexcept, synchronized, transaction_safe, transaction_safe_dynamic

[编辑] 编译器支持

此技术规范自 GCC 6.1 版起受支持(需要启用 -fgnu-tm)。此规范的旧版本自 GCC 4.7 起 受支持