问题描述
编译器会重新排列由mutex
保护的指令吗?我正在使用boolean
变量来确定一个线程是否已更新某些结构.如果编译器对指令重新排序,则可能会在更新结构的所有字段之前设置boolean
变量.
Will the compiler reorder instructions which are guarded with a mutex
? I am using a boolean
variable to decide whether one thread has updated some struct. If the compiler reorders the instructions, it might happen that the boolean
variable is set before all the fields of the struct are updated.
struct A{
int x;
int y;
// Many other variables, it is a big struct
}
std::mutex m_;
bool updated;
A* first_thread_copy_;
// a has been allocated memory
m_.lock();
first_thread_copy_->x = 1;
first_thread_copy_->y = 2;
// Other variables of the struct are updated here
updated = true;
m_.unlock();
在另一个线程中,我只是检查结构是否已更新并交换指针.
And in the other thread I just check if the struct has been updated and swap the pointers.
while (!stop_running){
if (updated){
m_.lock();
updated = false;
A* tmp = second_thread_copy_;
second_thread_copy_ = first_thread_copy_;
first_thread_copy_ = tmp;
m.unlock();
}
....
}
我的目标是保持第二个线程尽可能快.如果发现更新尚未发生,它将继续并使用旧值执行剩余的工作.
My goal is to keep the second thread as fast as possible. If it sees that update has not happened, it continues and uses the old value to do the remaining stuff.
一种避免重新排序的解决方案是使用memory barriers
,但是我正在尝试避免在mutex
块中使用它.
One solution to avoid reordering would be to use memory barriers
, but I'm trying to avoid it within mutex
block.
推荐答案
您可以放心地假设在锁/解锁和锁中的指令之间未对指令进行重新排序. updated = true
在解锁后或锁定之前不会发生.两者都是障碍,并防止重新排序.
You can safely assume that instructions are not reordered between the lock/unlock and the instructions inside the lock. updated = true
will not happen after the unlock or before the lock. Both are barriers, and prevent reordering.
您不能假设锁中的更新是在没有重新排序的情况下发生的. updated
的更新可能发生在x或y的更新之前.如果您的所有访问权限也都处于锁定状态,那应该没问题.
You cannot assume that the updates inside the lock happen without reordering. It is possible that the update to updated
takes place before the updates to x or y. If all your accesses are also under lock, that should not be a problem.
请记住,请注意,不仅编译器可能会重新排序指令. CPU也可能会不按顺序执行指令.
With that in mind, please note that it is not only the compiler that might reorder instructions. The CPU also might execute instructions out of order.
这篇关于带锁的指令重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!