考虑到这些条件,我可以使用 STL 进行线程处理吗?

发布于 2024-07-26 08:59:41 字数 210 浏览 1 评论 0原文

我有一个以下形式的集合:

map<key, list<object> >

我只在列表的后面插入,有时我从整个地图中读取(但我从不写入地图,除非在初始化时)。

据我了解,没有一个 STL 容器是线程安全的,但我实际上每个键最多只能有一个线程。 如果我假设这样的安排会很安全,我是否错过了什么?

I have a collection of the form:

map<key, list<object> >

I only ever insert at the back of the list and sometimes I read from the entire map (but I never write to the map, except at initialization).

As I understand it, none of the STL containers are thread safe, but I can only really have a maximum of one thread per key. Am I missing anything in assuming I'll be pretty safe with this arrangement?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

瀟灑尐姊 2024-08-02 08:59:41

如果在多线程场景中地图从未被修改,那么就没有问题。 如果每个线程查看自己的列表,那么这就是线程私有数据,所以你也可以。

请注意不要尝试使用 [] 查找键,因为如果映射中尚不存在该键,则会插入(修改)。

但是,我很好奇为什么需要这个结构 - 为什么不在每个线程的堆栈上保留指针/引用或实际列表对象本身,因为它是每个线程私有的?

(如果不是,那么您需要在列表上进行适当的同步。)

事实上,您说您“从整个映射中读取” - 大概意味着任何随机线程都可能尝试迭代任何列表。 所以你肯定需要同步列表上的操作。

If the map is never modified at all during the multi-threaded scenario, then you're fine. If each thread looks at its own list, then that's thread-private data, so you're also fine.

Take care not to try and lookup keys with [] because that will insert (modify) if the key doesn't exist in the map yet.

However, I'm curious as to why you'd need this structure - why not keep a pointer/reference or the actual list object itself on the stack of each thread, given that it's private to each thread?

(If it's not, then you need proper synchronisation on the list.)

In fact you say you "read from the entire map" - presumably meaning that any random thread may try to iterate through any of the lists. So you definitely need to synchronise operations on the lists.

故笙诉离歌 2024-08-02 08:59:41

老实说,只要您在任何写入和读取周围放置一个关键部分,它就会正常工作。

TBH as long as you put a critical section around any write and read it will work fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文