关于STL线程安全和STL调试的问题

发布于 2024-08-28 12:31:43 字数 93 浏览 1 评论 0原文

我有两个关于STL的问题

1)为什么STL不是线程安全的?有没有线程安全的结构?

2)如何使用GDB调试STL?在GDB中,如何打印矢量?

I have two questions about STL

1) why STL is not thread-safe? Is there any structure that is thread-safe?

2) How to debug STL using GDB? In GDB, how can I print a vector?

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

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

发布评论

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

评论(4

风透绣罗衣 2024-09-04 12:31:44
  1. 容器数据结构几乎总是需要同步(例如互斥体)以防止竞争条件。由于 C++ 标准(C++0x 之前)不支持线程,因此无法将它们添加到 STL 中。此外,在不需要同步的情况下,同步的成本非常高。只要您手动执行此同步,STL 容器就可以在多线程应用程序中使用。或者,您可以创建自己的与 STL 算法兼容的线程安全容器,例如 这个线程安全循环队列
  2. 向量包含一个连续的内存块。因此,一旦找到指向该内存块的指针,它就可以像常规数组一样显示。确切的细节取决于您使用的 STL 实现。
  1. Container data structures almost always require synchronization (e.g. a mutex) to prevent race conditions. Since threading is not support by the C++ standard (pre C++0x), these could not be added to the STL. Also, synchronization is very expensive for cases where it is not needed. STL containers may be used in multi-threaded applications as long as you perform this synchronization manually. Alternatively, you may create your own thread-safe containers that are compatible with STL algorithms like this thread-safe circular queue.
  2. A vector contains a contiguous block of memory. So, it can be displayed in the same way as a regular array once you find the pointer to this memory block. The exact details depend on the STL implementation you use.
风吹短裙飘 2024-09-04 12:31:44

标准 C++ 容器不是线程安全的,因为您很可能实际上需要比容器本身更高级别的锁定。换句话说,您可能希望两个或多个操作一起安全进行。

例如,如果您有多个线程正在运行:

v.push_back(0);
v.push_back(1);

不会获得交替的 0 和 1 的良好向量,它们可能会混乱。您需要锁定这两个命令才能获得您想要的结果。

The standard c++ containers are not thread safe because you most likely actually want higher level locking than just the containers themselves. In other words you are likely to want two or more operations to be safe together.

For example, if you have multiple threads running:

v.push_back(0);
v.push_back(1);

You wont get a nice vector of alternating 0's and 1's, they could be jumbled. You would need to lock around both commands to get what you want.

琴流音 2024-09-04 12:31:44

STL 不是线程安全的,因为很多人不需要线程安全,并且因为这将线程上下文引入到类中,否则这些类不需要了解任何有关线程概念的信息。

您可以封装对容器的访问并提供您自己的线程安全性(或您的特定设计和实现所施加的其他限制。)

STL is not thread-safe because a lot of people don't need thread safety, and because that introduces threading context into classes that otherwise have no need to know anything about the concept of threads.

You can encapsulate access to containers and provide your own thread safety (or other restrictions imposed by your specific design and implementation.)

和影子一齐双人舞 2024-09-04 12:31:44
  1. 因为仍然存在单线程程序。
  2. 请查看此处
  1. Because there are still single-threaded programs.
  2. Take a look here.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文