Do I need to protect read access to an STL container in a multithreading environment?(在多线程环境中是否需要保护对 STL 容器的读取访问?)
问题描述
我有一个 std::list<> 容器和这些线程:
I have one std::list<> container and these threads:
一个无限添加元素的作家线程.
One writer thread which adds elements indefinitely.
一个读取器/写入器线程,在可用时读取和删除元素.
One reader/writer thread which reads and removes elements while available.
多个读取器线程访问容器的 SIZE(通过使用 size() 方法)
Several reader threads which access the SIZE of the container (by using the size() method)
有一个普通的互斥锁来保护前两个线程对列表的访问.我的问题是,大小读取器线程是否也需要获取此互斥锁?我应该使用读/写互斥锁吗?
There is a normal mutex which protects the access to the list from the first two threads. My question is, do the size reader threads need to acquire this mutex too? should I use a read/write mutex?
我在使用 Visual C++ 6 的 Windows 环境中.
I'm in a windows environment using Visual C++ 6.
更新:看起来答案还不清楚.总结一下主要的疑问:考虑到我不需要确切的值(即我可以假设一个+/- 1 个变化)?竞争条件如何使我的 size() 调用返回无效值(即与好的值完全无关的值)?
Update: It looks like the answer is not clear yet. To sum up the main doubt: Do I still need to protect the SIZE reader threads even if they only call size() (which returns a simple variable) taking into account that I don't need the exact value (i.e. I can assume a +/- 1 variation)? How a race condition could make my size() call return an invalid value (i.e. one totally unrelated to the good one)?
答案:通常,必须保护读取器线程以避免竞争条件.尽管如此,在我看来,更新中提到的一些问题还没有得到解答.
Answer: In general, the reader threads must be protected to avoid race conditions. Nevertheless, in my opinion, some of the questions stated above in the update haven't been answered yet.
提前致谢!
谢谢大家的回答!
推荐答案
是的,读取线程需要某种互斥控制,否则写入会改变它下面的内容.
Yes, the read threads will need some sort of mutex control, otherwise the write will change things from under it.
一个读写器互斥锁就足够了.但严格来说,这是一个特定于实现的问题.即使在代码中只读的 const 对象中,实现也可能具有可变成员.
A reader/writer mutex should be enough. But strictly speaking this is an implmentation-specific issue. It's possible that an implementation may have mutable members even in const objects that are read-only in your code.
这篇关于在多线程环境中是否需要保护对 STL 容器的读取访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在多线程环境中是否需要保护对 STL 容器的读取访问?
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01