如果我将内存栅栏放在子函数中而不是放在使用数据的函数中,那么线程安全是否存在差异。
底部示例包括两个版本。我想知道是否存在我不知道的差异。函数A_function
和B_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;
}