-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
谈谈 C++ 中的内存顺序 (Memory Order) - Luyu Huang's Tech Blog #69
Comments
大佬讲得很好,用例也很能体现讲解的知识点~ |
谢谢! 不是大佬 😂 |
“总结”一节里的第一项是不是应该是“relaxed”? |
确实. 感谢指正! |
3.4 节中这里的说法是错误的吧,实际上 thread2 在 RMW 操作后读 data 是安全的. |
不安全吧,因为那个 RMW 操作是 relaxed。这个回答也说了
|
大佬讲的很棒! |
Do you know that sobyte.net has translated your article into English, published it at https://www.sobyte.net/post/2022-06/cpp-memory-order/ next to many other articles taken from Chinese websites and translated, and put their own ads on the article? Was this done without your permission? |
Yes I knew that, they didn't get my permission. I don't know if I have a way to stop them from doing that. |
写得挺好,不过C++11实现多线程条件下的单例模式使用静态局部变量只初始化一次且线程安全的语法特性就行了,不用加锁 class Singleton
{
public:
static Singleton& getInstance()
{
static Singleton value;
return value;
}
private:
Singleton() = default;
Singleton(const Singleton &rhs) = delete;
Singleton &operator=(const Singleton &rhs) = delete;
}; |
是的,感谢补充! |
大佬写的很好!!! |
谢谢!还不是大佬。祝你新年快乐! |
Hi 打扰了,我有个地方不明白。还请大牛指教下。谢谢啦。 void thread2() { void read_x_then_y() { void read_y_then_x() { 则最终不能保证 z 不为 0. 在同一次运行中, read_x_then_y 有可能看到先 (1) 后 (2), 而 read_y_then_x 有可能看到先 (2) 后 (1). 这样有可能 (4) 和 (6) 的 load 的结果都为 false, 导致最后 z 仍然为 0. 要么 先 (1) 后 (2),要么 先 (2) 后 (1);但无论哪种 read_x_then_y 与 read_y_then_x,都会有一个能执行++z的吧? |
还有这个: 我觉得,memory_order_acquire会将lock前的操作,重排到lock后;相当于扩大了锁的范围。是不是改为 memory_order_acq_rel 更恰当些。 最近在学习Rust,看到了这部分。之前的java经验,对这部分很陌生。看了两三遍,仍然不能够确定自己的理解。还请大佬给确认下。谢谢 |
从实现的角度来说,如果 |
我觉得没事吧。如果编译器觉得那个指令放后面更合适,那大概率它更后面的代码相关性很大,就让它放呗。基本上我们的原则就是使用尽可能宽松的内存顺序,让编译器做更多的优化。当然如果测试验证某个场景下 acq_rel 跑得更快,也是可以作专项优化调整的。 |
多谢回答! |
醍醐灌顶! |
老哥过誉了😂 |
写的很不错,比知乎那些详细多了,而且很有逻辑~ |
谢谢大佬讲解,获益良多 |
https://luyuhuang.tech/2022/06/25/cpp-memory-order.html
C++11 将多线程纳入了标准. 一旦涉及到多线程, 就需要考虑并发, 数据竞争 (date race), 线程同步等问题, 为此 C++ 提供了互斥锁 std::mutex, 原子变量 std::atomic 等标准库. 对于原子变量的操作, 有一个很重要的概念就是内存顺序 (memory order), 其中...
The text was updated successfully, but these errors were encountered: