vendredi 24 juin 2022

How does atomic seq_cst memory order actually work?

For example, there are shared variables.

int val;
Cls obj;

An atomic bool variable acts as an data indicator.

std::atomic_bool flag = false;

Thread 1 only set these variables.

while (flag == true) { /* Sleep */ }

val = ...;
obj = ...;

flag = true; /* Set flag to true after setting shared variables. */

Thread 2 only get these variables.

while (flag != true) { /* Sleep */ }

int local_val = val;
Cls local_obj = obj;

flag = false; /* Set flag to false after using shared variables. */

My questions are:

  1. For std::memory_order_seq_cst, which is default for std::atomic_bool, is it safe to set or get shared variables after while (...) {}?

  2. Using bool instead of std::atomic_bool is correct or not?

Aucun commentaire:

Enregistrer un commentaire