在多线程环境中是否需要保护对 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.
相关文章