我需要在多线程环境中保护对STL容器的读访问权限吗? [英] Do I need to protect read access to an STL container in a multithreading environment?

查看:95
本文介绍了我需要在多线程环境中保护对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)

它保护从前两个线程对列表的访问。我的问题是,做大小读取器线程需要获取这个互斥吗?我应该使用读/写mutex?

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.

更新:看起来还不清楚答案。总结主要的疑问:我仍然需要保护SIZE阅读器线程,即使他们只调用size()(它返回一个简单的变量),考虑到我不需要确切的值(即我可以假设+/- 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容器的读访问权限吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆