gpt4 book ai didi

c++ - 一位读者。一位作家。关于互斥量和原子内置函数的一些一般性问题

转载 作者:可可西里 更新时间:2023-11-01 18:15:17 25 4
gpt4 key购买 nike

我有一个共享 bool 标志和 std::vector 的父线程和工作线程。父级只读取(即读取 bool 或调用 my_vector.empty()); worker 只会写。

我的问题:

  • 我是否需要互斥锁来保护 bool 标志?

  • 我可以说所有 bool 读/写本质上都是原子操作吗?如果您回答"is"或“否”,您从哪里获得信息?

  • 我最近听说了 GCC Atomic-builtin .我可以使用这些使我的标志读/写原子而不必使用互斥锁吗?有什么区别?我了解 Atomic 内置函数归结为机器代码,但即使是互斥锁也归结为 CPU 的内存屏障指令,对吧?为什么人们称互斥锁为“操作系统级”结构?

  • 我需要互斥锁来保护我的 std::vector 吗?回想一下,工作线程填充此 vector ,而父线程仅对其调用 empty()(即仅读取它)

  • 我认为 bool 或 vector 都不需要互斥保护。我合理化如下,“好吧,如果我在更新之前读取共享内存......那仍然很好,我会在下一次获得更新的值。更重要的是,我不明白为什么 writer 应该被阻止而同时读书就是读书,毕竟读者只是在读书!”

如果有人能给我指出正确的方向,那就太好了。我在 GCC 4.3 和 Intel x86 32 位上。非常感谢!

最佳答案

Do I need to mutex protect the bool flag?

不一定,原子指令就可以。 atomic instruction 我的意思是编译器内部函数 a) 防止编译器重新排序/优化和 b) 导致原子读/写和 c) 发出适当的内存栅栏以确保 CPU 之间的可见性(对于当前使用 MESI cache coherency protocol 的 x86 CPU)。类似于 gcc atomic builtins .

Can I say that all bool read/writes are inherently atomic operations? If you say Yes or No, where did you get your information from?

取决于 CPU。对于英特尔 CPU - 是的。参见 Intel® 64 and IA-32 Architectures Software Developer's Manuals .

I recently heard about GCC Atomic-builtin. Can I use these to make my flag read/writes atomic without having to use mutexes? What is the difference? I understand Atomic builtins boil down to machine code, but even mutexes boil down to CPU's memory barrier instructions right? Why do people call mutexes an "OS-level" construct?

原子和互斥量的区别在于后者可以让等待线程休眠直到互斥量被释放。使用原子,您只能忙转。

Do I need to mutex protect my std::vector? Recall that the worker thread populates this vector, whereas the parent only calls empty() on it (i.e., only reads it)

是的。

I do not believe mutex protection is necessary for either the bool or the vector. I rationalize as follows, "Ok, if I read the shared memory just before it was updated.. thats still fine, I will get the updated value the next time around. More importantly, I do not see why the writer should be blocked while the reading is reading, because afterall, the reader is only reading!"

根据实现,vector.empty() 可能涉及读取两个缓冲区开始/结束指针并减去或比较它们,因此您有可能读取一个指针的新版本并且另一个没有互斥量的旧版本。可能会发生令人惊讶的行为。

关于c++ - 一位读者。一位作家。关于互斥量和原子内置函数的一些一般性问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7081176/

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