Теперь есть несколько потоков считывателей. Каждый поток считывает значение x и y . Идея состоит в том, что если есть < /p>
"один глобальный заказ" < /p>
< /blockquote>
Тогда {x = 0, y = 1} и {x = 1, y = 0} не видно вместе. std :: atomic готово . Готовый флаг похож на спусковой крючок. Все потоки могут запустить свою соответствующую логику только после того, как готова - true
Но удивительно, я получаю результат {0,1} и {1,0} на моей машине.
Код: Выделить всё
#include
#include
#include
#include
static constexpr std::size_t ITERATIONS = 1000000;
static constexpr std::size_t NUM_THREADS = 10;
using result = std::pair;
std::vector results;
std::atomic_bool ready;
std::atomic x, y;
void initialize()
{
results.clear();
results.resize(NUM_THREADS, {0, 0});
ready.store(false, std::memory_order_seq_cst);
x.store(0, std::memory_order_seq_cst);
y.store(0, std::memory_order_seq_cst);
}
void modify_x()
{
while (!ready.load(std::memory_order_seq_cst))
;
x.store(1, std::memory_order_seq_cst);
}
void modify_y()
{
while (!ready.load(std::memory_order_seq_cst))
;
y.store(1, std::memory_order_seq_cst);
}
void check(int i)
{
while (!ready.load(std::memory_order_seq_cst))
;
int xl = x.load(std::memory_order_seq_cst);
int yl = y.load(std::memory_order_seq_cst);
results[i] = {xl, yl};
}
bool check_results()
{
// stores count of {0, 0}, {0, 1}, {1, 0}, {1, 1}
int arr[4] = {0, 0, 0, 0};
for (const auto &res : results)
{
if (res.first == 0 && res.second == 0)
arr[0]++;
else if (res.first == 0 && res.second == 1)
arr[1]++;
else if (res.first == 1 && res.second == 0)
arr[2]++;
else if (res.first == 1 && res.second == 1)
arr[3]++;
}
bool success = arr[1] != 0 && arr[2] != 0;
if (success)
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79699895/how-does-the-single-global-order-in-stdmemory-order-seq-cst-work[/url]