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 容器的读取访问?


基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09