XPCOM Thread Synchronization

XPCOM thread synchronization primitives have the same semantics as those in NSPR, and each method of these synchronization objects (e.g. Mutex::Lock()) has a matching function in NSPR (PR_Lock()). This is no accident, as mozilla:: primitives are merely bare-minimum wrappers around NSPR's.

This article covers the API of Mozilla synchronization only. For a higher-level introduction to thread synchronization, see Introduction_to_NSPR.

Quick reference: Difference between nsAutoLock API and new API

Old construction

 

Note: This is deprecated code that is shown only to compare with approved code.
  PRLock* mLock;
  PRMonitor* mMonitor;
  PRCondVar* mCvar;
  FooConstructor() {
  }
  nsresult Init() {
      mLock = nsAutoLock::NewLock("Foo lock");
      // check for null
      mMonitor = nsAutoMonitor::NewMonitor("Foo monitor");
      // check for null
      mCvar = PR_NewCondVar(mRawLock);
      // check for null
      // ...
  }

 

New Construction

 

  using namespace mozilla;
  Mutex mLock;
  Monitor mMonitor;
  CondVar mCvar;
  FooConstructor() 
      : mLock("Foo lock"),
        mMonitor("Foo monitor"),
        mCvar(mLock, "Foo condvar") {
  }
  nsresult Init() {
      // ...
  }

 

Old Usage

 

Note: This is deprecated code that is shown only to compare with approved code.
  ConcurrentMethod() {
      nsAutoLock al(mLock);
      nsAutoMonitor am(mMonitor);
      if (needExpensiveComputation()) {
          nsAutoUnlock au(mLock);
      }
      am.Wait();
      PR_NotifyCondVar(mCvar);
  }

 

New Usage

 

  using namespace mozilla;
  ConcurrentMethod() {
      MutexAutoLock al(mLock);
      MonitorAutoEnter am(mMonitor);
      if (needExpensiveComputation()) {
          MutexAutoUnlock au(mLock);
      }
      am.Wait();
      mCvar->Notify();
  }

 

Mozilla Synchronization API reference

The mozilla:: namespace exports the following synchronization primitives.

Document Tags and Contributors

 Contributors to this page: teoli, cgj
 Last updated by: cgj,