Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instruction reordering with lock

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.

One solution to avoid reordering would be to use memory barriers, but I'm trying to avoid it within mutex block.

like image 712
nishantsingh Avatar asked Mar 15 '26 01:03

nishantsingh


1 Answers

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.

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.

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.

like image 173
Shachar Shemesh Avatar answered Mar 16 '26 14:03

Shachar Shemesh