std :: vector线程安全吗? [英] Is std::vector thread safe ?

查看:203
本文介绍了std :: vector线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在多线程环境中使用std :: vector.所有对象都在向量的不同元素上工作.但是我观察到,向量操作在多线程环境中花费的时间比在单线程中花费的时间更多.

矢量线程是否安全,这可能会导致延迟


预先感谢.

Hi,

I am using std::vector in a multithreaded envioronment. All threds work on diffferent elements of the vector. But what i observed is vector operations are taking more time in multithreaded env than in single threaded.

Is vector thread safe which might be causing the delay


Thanks in advance.

推荐答案

请参见

Richard指出的讨论只不过是一种复杂的表达方式
您可以通过查看源代码看到不,不对集合和元素本身进行锁定"(不容易,因为大量的宏和定义混淆了真实的代码).没有防止线程冲突的方法.

观察到的不同时序不是由于锁定",而是由于无法将所有迭代管理到内核的一级缓存中:如果各个线程托管在不同的内核上,则每次写操作都需要对RAM进行访问,每次后续阅读.
The discussion pointed out by Richard is nothing more than a complicated way to say
"no: no locking is done on the collection and on elements themselves", as you can (not easily, because of lot of macros and definitions that obfuscate the real code) see by looking the source code. There is nothing protecting against threads conflicts.

The different timing observed is not due to "locking" but to the impossibility to manage all the iteration into the 1st level cache of a core: if the various threads are hosted on different cores, a RAM access is required for every single write, an every subsequent read.


尽管有其他解决方案,但我仅提供一些类比和提示,可能有助于了解它的安全性...

安全性与动态分配的C数组所期望的安全性非常相似.

知道哪些操作会使迭代器无效,这也将有助于理解可以安全执行的操作.
Although other solutions are goods, I will just provide some analogies and hints that might help understand how safe it is...

Safety would be very similar to what you would expected from a dynamically allocated C array.

Knowing which operations can invalidate iterators would also help to understand what would be safe to do.


这篇关于std :: vector线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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