[LLVMbugs] [Bug 19766] New: std::mutex initialization is unsafe on iOS

bugzilla-daemon at llvm.org bugzilla-daemon at llvm.org
Fri May 16 21:35:17 PDT 2014


            Bug ID: 19766
           Summary: std::mutex initialization is unsafe on iOS
           Product: libc++
           Version: 3.4
          Hardware: Other
                OS: other
            Status: NEW
          Severity: normal
          Priority: P
         Component: All Bugs
          Assignee: unassignedclangbugs at nondot.org
          Reporter: bstrong at gmail.com
                CC: llvmbugs at cs.uiuc.edu, mclow.lists at gmail.com
    Classification: Unclassified

The std::mutex constructor initializes the pthread_mutex member with
PTHREAD_MUTEX_INITIALIZER (a macro intended to be used for initializing static
mutexes). This macro does not do real initialization, but instead sets a flag
that results in actual initialization being done on the first call to

On most modern pthreads implementations, this deferred initialization is thread
safe (i.e., if the first call to pthread_mutex_lock() occurs simultaneously on
two different threads, the right thing happens). Unfortunately, some
implementations, notably the one on iOS, do not do the right thing. 

For an example of an unsafe implementation of deferred initialization, see:

The correct, portable way to initialize a pthread_mutex member variable is with
pthread_mutex_init() (as the libstdc++ and boost mutex implementations do).

The following code snippet will throw from mutex::lock() with libc++ on iOS (it
works with libc++ on OSX and linux and with libstdc++ and boost mutex
implementations on iOS):

  for (int i = 0; i < 1000; ++i) {
    std::array<std::mutex, 1000> mutexes;
    auto thread_fn = ([&mutexes]() {
      for (auto& m : mutexes) {
    thread t1(thread_fn);
    thread t2(thread_fn);

This was tested with the libdc++ included with Xcode 5.1.1 on an iPad3 running
iOS 7.1.1.

You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20140517/c3d968d1/attachment.html>

More information about the llvm-bugs mailing list