简体   繁体   中英

Does std::atomic prevent reordering of nonatomic variables over the atomic variables

question is rather simple Q: If I have

settings[N_STNGS];//used by many threads  
std::atomic<size_t> current_settings(0);
void updateSettings()//called by single thread  , always the same thread if that is important
{

    auto new_settings = (current_settings+1)%N_STNGS;
    settings[new_settings].loadFromFileSystem(); //line A
    current_settings=new_settings; //line B
}

does standard guarantee that line A wont be reordered after line B? Also will users of STNGS always see consistent(commited-as in memory visibility visible) data?

Edit: for multiple reader threads and nontrivial settings is this worth the trouble compared to simple mutexing?

Given the definition

int settings[N_STNGS];
std::atomic<size_t> current_settings(0);

and Thread 1 executing:

settings[new_settings] = somevalue;  // line A
current_settings=new_settings;       // line B

and Thread 2 executing:

int cur_settings = current_settings;        // line X
int setting_value = settings[cur_settings]; // line Y

then yes, if Thread 2 at line X reads new_settings written by Thread 1 in line B, and there are no other modifications to settings[new_settings] (by some code we don't see), Thread 2 is bound to read somevalue and no undefined behavior occurs. This is because all the operations are (by default) memory_order_seq_cst and a release-write (line B) synchronizes with an acquire-read (line X). Note that you need two statements in Thread 2 to get a sequenced-before relationship between the atomic read of the index and the read of the value (a memory_order_consume operation would do instead).

I'd certainly implement it with rw-mutexes for start.

The general answer is no. If you are careful and you use only functions which have a memory_order parameter and pass them the right value for it depending on what you are doing, then it may be yes.

(And as other have pointed out, your code has problems. For instance, returning by value an atomic<> type doesn't make sense for me.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM