本文介绍了没有原子的 C++ 线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解原子为多线程程序提供了保证,但是在下面的情况下,如果我不使用原子有什么问题吗?

I understand that atomics provides guarantees for multithreaded programs, but in the following case, is there any problem if I don't use atomics?

struct Foo  {
  Foo() : a(0) {
    findA(&a);
  }

  int a;
}

void findA(int *a) {
  // spaws a thread...
  // the following runs on a separate thread
  *a = 5; // find the actual value of a (5 for example)
}

一旦构造函数完成,其他线程将永远不会写入a,那么我可以在不锁定的情况下安全地读/写它吗?

Once the constructor is done, no other thread will ever write to a, so can I safely read/write to it without locking?

推荐答案

C++ 内存模型指出,如果一个线程写入一个变量而另一个线程在没有对这些操作进行排序的情况下读取,则无法保证程序在全部.

The C++ memory model states that if one thread writes to a variable and another reads without those operations being sequenced, no guarantees are placed on the operation of the program at all.

有很多方法可以对访问进行排序;原子只是其中之一.但是这种UB真的很容易在幼稚的多线程代码中触发.

There are a bunch of ways to sequence access; atomics is just one of them. But this kind of UB is really easy to trigger in naive multithreaded code.

该规则的目标是允许推理单线程本地状态.例如,如果一个线程从 a 读取 7,并且它知道它没有同步,也没有任何可以编辑 a 的操作,它会不必从内存中重新加载它、清除 CPU 缓存或任何此类开销.它会知道值仍然是 7.

A goal of that rule is to permit single threads local state to be reasoned about. For example, if a thread reads 7 from a, and it knows it did no synchronization, nor any operation that could edit a, it does not have to reload it from memory, clear cpu caches, or any of that overhead. It will know the value remains 7.

这篇关于没有原子的 C++ 线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:07