子函数中的内存栅栏 vs 与数据更改相同的函数

memory fences in subfunction vs in the same function as the data change

如果我将内存栅栏放在子函数中而不是放在使用数据的函数中,线程安全性是否存在差异。 底部示例包括两个版本。我想知道是否存在我不知道的差异。函数 A_functionB_function 是否同样是线程安全的?

#include<atomic>

using std::atomic;
using std::atomic_thread_fence;
using std::memory_order_acquire;
using std::memory_order_release;

typedef struct 
{
    atomic<int> lock;
    int counter;
}Data;

void A_acquire(atomic<int> * lock);
void A_release(atomic<int> * lock);
void A_function(Data * data);
void B_acquire(atomic<int> * lock);
void B_release(atomic<int> * lock);
void B_function(Data * data);

void A_acquire(atomic<int> * lock)
{
    int ticket = lock->fetch_add(1);
    while (0 != ticket)
    {
        lock->fetch_sub(1);
        ticket = lock->fetch_add(1);
    }
    //DIFFERENCE HERE
}

void A_release(atomic<int> * lock)
{
    //DIFFERENCE HERE
    lock->fetch_sub(1);
}

void A_function(Data * data)
{
    A_acquire(&data->lock);
    atomic_thread_fence(std::memory_order_acquire); //DIFFERENCE HERE
    data->counter += 1;
    atomic_thread_fence(std::memory_order_release); //DIFFERENCE HERE
    A_release(&data->lock);
}

void B_acquire(atomic<int> * lock)
{
    int ticket = lock->fetch_add(1);
    while (0 != ticket)
    {
        lock->fetch_sub(1);
        ticket = lock->fetch_add(1);
    }
    atomic_thread_fence(std::memory_order_acquire); //DIFFERENCE HERE
}

void B_release(atomic<int> * lock)
{
    atomic_thread_fence(std::memory_order_release); //DIFFERENCE HERE
    lock->fetch_sub(1);
}

void B_function(Data * data)
{
    B_acquire(&data->lock);
    //DIFFERENCE HERE
    data->counter += 1;
    //DIFFERENCE HERE
    B_release(&data->lock);
}

int main(void)
{
    Data dat = { 0, 0 };
    A_function(&dat);
    B_function(&dat);
    return 0;
}

A_functionB_function 在语义上没有区别。内存栅栏效应不受函数体的限制。

此外,正如 Phantom 指出的那样,您示例中的内存栅栏是不必要的:fetch_sub()fetch_add() 都已经具有获取 + 释放语义。

但通过以下修改,释放抓取变得至关重要:

void A_acquire(atomic<int> * lock)
{
    int ticket = lock->exchange(1);
    while (0 != ticket)
    {
        ticket = lock->exchange(1);
    }
    //DIFFERENCE HERE
}

void A_release(atomic<int> * lock)
{
    //DIFFERENCE HERE
    lock->store(0, memory_order_relaxed);
}