Is it safe to use the Structure dereference(->) operator on the result of std::atomic::load

时间:2015-05-08 10:07:59

标签: c++ c++11 atomic stdatomic

Whilst trying to work with std atomic pointer, I ran into the following. Say I do this:

.row {
    background-color: #ccc;
}

I'm pretty sure C is illegal because myString might be deleted in the meantime.

However I'm unsure about A and B. I suppose they are illegal since the pointer might be deferenced whilst performing the read operation.

However if this is the case, how can you ever read from an atomic pointer that might be deleted. Since the load is 1 step, and the reading of the data is 1 step.

1 个答案:

答案 0 :(得分:2)

有人提到你的方法是有风险的业务。您可能需要考虑以下内容:将std::shared_ptr<const std::string>与不可变值和shared_ptr atomic_load and atomic_store一起使用。 std::shared_ptr将确保您不访问悬空指针,而不变性(字符串在构造后不会更改)将保证对字符串本身的访问是线程安全的,因为所有const方法都由标准是线程安全的。

编辑:根据要求解释我的意思&#34;风险商业&#34;:如果您使用std::atomic<std::string *>,那么很容易意外引入竞争条件,例如

// Data
std::atomic<std::string *> str(new std::string("foo"));

// Thread 1
std::cout << *str.load();

// Thread 2
*str.load() = "bar"; // race condition with read access in thread 1

// Thread 2 (another attempt using immutable instances)
auto newStr = new std::string("bar");
auto oldStr = str.exchange(newStr);
delete oldStr;  /* race condition with read access in thread 1
                   because thread 1 may have performed load() before
                   the exchange became visible to it, and may not
                   be finished using the old object. */

请注意,这与operator <<无关,即使只是在线程1中的字符串上调用size()也会导致竞争条件。

在实践中,人们可能会看到&#34;修复&#34;比如在更新中使用不可变字符串在sleep之前添加delete,以便线程1有足够的时间用旧指针完成其业务。虽然在特定实现中这可能大部分时间,但它并没有引入真正的排序(发生在关系之前,在C ++标准中),因此不是正确的rsp。便携式解决方案。