gpt4 book ai didi

c++ - 指向用户定义对象的 C++ 指针是否可以线程安全读取?

转载 作者:太空狗 更新时间:2023-10-29 19:46:17 27 4
gpt4 key购买 nike

我找不到答案,但这是一个简单的问题:

在没有锁或任何其他恶作剧的情况下,两个线程在 c++ 中同时读取指向用户定义对象的指针的值是否安全?

最佳答案

是的。实际上,同时读取任何值(内置类型)是安全的。

数据竞争只会发生,如果一个值被同时修改与其他线程使用它。标准中对此的关键陈述是:

数据竞争在 §1.10/21 中定义:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other.

在 §1.10/4 中定义了冲突:

Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

因此您必须在这些读取和任何写入之间使用合适的同步。

关于c++ - 指向用户定义对象的 C++ 指针是否可以线程安全读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14713649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com