简体   繁体   English

线程安全数据和线程安全容器

[英]Thread Safe Data and Thread Safe Containers

嗨,大家好,我想知道线程安全数据和线程安全容器之间的区别是什么

Thread safe data : 线程安全数据

  • Generally refers to data which is protected using mutexes , semaphores or other similar constructs. 通常是指使用互斥 信号量或其他类似构造进行保护的数据。

  • Data is considered thread safe if measures have been put in place to ensure that: 如果已采取措施确保:

    • It can be modified from multiple threads in a controlled manner, to ensure the resultant data structure doesn't becoming corrupt, or lead to race conditions in the code. 可以从多个线程以受控方式对其进行修改 ,以确保结果数据结构不会损坏,也不会导致代码中的竞争条件。
    • It can be read in a reliable fashion without the data become corrupt during the read process. 可以以可靠的方式读取它,而在读取过程中数据不会损坏。 This is especially important with STL-style containers which use iterators. 这对于使用迭代器的STL样式的容器尤其重要。
  • Mutexes generally work by blocking access to other threads while one thread is modifying shared data. 互斥体通常通过在一个线程修改共享数据时阻止对其他线程的访问来工作。 This is also known as a critical section , and RAII is a common design pattern used in conjunction with critical sections. 这也称为关键部分RAII是与关键部分结合使用的常见设计模式。

  • Depending on the CPU type, some primitive data types (eg int) and operations (increment) might not need mutex protection (eg if they resolve down to an atomic instruction in machine language). 根据CPU类型,某些原始数据类型(例如int)和操作(递增)可能不需要互斥保护(例如,如果它们分解为机器语言中的原子指令)。 However: 然而:

    • It is bad practice to make any assumptions about CPU architecture. 对CPU体系结构进行任何假设都是不好的做法。
    • You should always code defensively to ensure code will remain thread-safe regardless of the target platform. 您应该始终进行防御性编码,以确保无论目标平台是什么,代码都将保持线程安全。

Thread safe containers : 穿线安全的容器

  • Are containers which have measures in place to ensure that any changes made to them occur in a thread-safe manner. 是已采取措施确保对它们所做的任何更改均以线程安全方式进行的容器。

  • For example, a thread safe container may allow items to be inserted or removed using a specific set of public methods which ensure that any code which uses it is thread-safe. 例如,线程安全容器可以允许使用一组特定的公共方法来插入或删除项目,以确保使用该线程的任何代码都是线程安全的。

  • In other words, the container class provides the mutex protection as a service to the caller, and the user doesn't have to roll their own. 换句话说,容器类将互斥保护作为服务提供给调用方,用户不必自己滚动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM