zoukankan      html  css  js  c++  java
  • boost::shared_ptr的线程安全性

    boost::shared_ptr的win32实现中,没有使用类似mutex机制却能够实现线程安全。

    线程安全主要就是保证引用计数机制的线程安全

    win32实现中关键在于使用了
    BOOST_INTERLOCKED_DECREMENT以及BOOST_INTERLOCKED_INCREMENT

    在interlocked.hpp中可以看到


    #if defined( BOOST_USE_WINDOWS_H )

    # include <windows.h>

    # define BOOST_INTERLOCKED_INCREMENT InterlockedIncrement
    # define BOOST_INTERLOCKED_DECREMENT InterlockedDecrement
    # define BOOST_INTERLOCKED_COMPARE_EXCHANGE InterlockedCompareExchange

    windows提供了InterlockedIncrement以及InterlockedDecrement两个api。
    实现 锁加,锁减操作。

    boost::shared_ptr的win32thread实现中,没有使用类似mutex机制却能够实现线程安全。
    boost::shared_ptr的pthread实现中,使用了mutex机制来保证线程安全。

    遗留疑问:
    InterlockedIncrement和InterlockedDecrement内部是否也使用了mutex机制?


    Boost 文档对于 shared_ptr 的线程安全有一段专门的记述,内容如下:
    shared_ptr objects offer the same level of thread safety as built-in types. A shared_ptr instance can be "read " (accessed using only const operations) simultaneously by multiple threads. Different shared_ptr instances can be "written to " (accessed using mutable operations such as operator= or reset) simultaneosly by multiple threads (even when these instances are copies, and share the same reference count underneath.)
    Any other simultaneous accesses result in undefined behavior.
    翻译为中文如下:
    shared_ptr 对象提供与内建类型一样的线程安全级别。一个 shared_ptr 实例可以同时被多个线程“读”(仅使用不变操作进行访问)。不同的 shared_ptr 实例可以同时被多个线程“写入”(使用类似 operator= 或 reset 这样的可变操作进行访问)(即使这些实例是拷贝,而且共享下层的引用计数)。
    任何其它的同时访问的结果会导致未定义行为。

  • 相关阅读:
    leetcode5 Longest Palindromic Substring
    leetcode17 Letter Combinations of a Phone Number
    leetcode13 Roman to Integer
    leetcode14 Longest Common Prefix
    leetcode20 Valid Parentheses
    leetcode392 Is Subsequence
    leetcode121 Best Time to Buy and Sell Stock
    leetcode198 House Robber
    leetcode746 Min Cost Climbing Stairs
    tomcat下使用druid配置jnid数据源
  • 原文地址:https://www.cnblogs.com/kex1n/p/2286430.html
Copyright © 2011-2022 走看看