简体   繁体   中英

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.
  • 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.

  • 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). However:

    • It is bad practice to make any assumptions about CPU architecture.
    • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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