Thread-safety Dance

By steve steve Permalink

While working out some threading issues with our GStreamer core, I spent some time on #developers getting answers to some XPCOM threading questions I’ve had for a long time.

The first question was about when to use NS_IMPL_ISUPPORTS versus NS_IMPL_THREADSAFE_ISUPPORTS when implementing XPCOM components in C++. The difference is in the way the reference counting methods are implemented — the former manages the reference count in a non-thread safe way, and the latter manages it in a thread safe way. Additionally, when running a debug build, components that use NS_IMPL_ISUPPORTS will assert if they are AddRefed/Released by any thread other than the owning thread (the thread the component was created on).

Therefore, you should be using NS_IMPL_THREADSAFE_ISUPPORTS if your component will be reference counted on more than one thread. If this will never happen, you should use NS_IMPL_ISUPPORTS to avoid the additional overhead of thread safe reference counting.

Note that using NS_IMPL_THREADSAFE_ISUPPORTS in your component implementation does not relate to the thread saftey of the component’s implementation, just the reference counting methods. If you wish to declare the fact that your component is implemented in a thread safe way, you must implement nsIClassInfo and set the nsIClassInfo::THREADSAFE bit in your GetFlags implementation.

By setting the nsIClassInfo::THREADSAFE bit, you are ensuring the users of your component that your component’s implementation is thread safe, meaning there is no sequence of operations involving multiple threads that will put your component into an invalid state, observe the component to be in an invalid state, or violate any of the class’s invariants, preconditions, or postconditions (this definition of thread safety is adapted from IBM DeveloperWorks’ Java theory and practice: Characterizing thread safety).

As the implementor, not only must your make sure your implementation is thread safe, but the XPCOM components you collaborate with must also be thread safe. This is why a component that touches the DOM can never be declared as thread safe unless the access to the DOM is done through a proxy.

Thanks to brendan and shaver on #developers for taking the time to clear this up for me!

Post a comment or Leave a trackback

1 Comment

Subscribe
  1. çeviri Jun 29, 2007 9:57 am Permalink

    As the implementor, not only must your make sure your implementation is thread safe, but the XPCOM components you collaborate with must also be thread safe. This is why a component that touches the DOM can never be declared as thread safe unless the access to the DOM is done through a proxy.
    tercüme
    ingilizce tercüme
    elektrik
    emlak çeviri
    tercüman link
    ekle
    kiralık ev

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

Comments on inactive posts are automatically sent to the moderation queue. Hang tight.