Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

C++ static locals share a global mutex? - deadlock issue



By default thread safe static locals are turned on in XCode. [GCC_THREADSAFE_STATICS]
ASAIK It means that when when the following function is called from multiple threads, it guarantees that foo is initialized only once.

void Foo() {
  static Foo foo;
}

Is it true that this feature uses a single(per process) lock?

It seems it not only causes a single static local statement to be thread safe, but also causes different static locals running on different threads to be serialized.

As a consequence it also means that static local-s are very prone to deadlocks. 
See the following (objc++) example, extracted from real world app:

#import <Cocoa/Cocoa.h>
#include <pthread.h>

void* ThreadFunction(void*)
{
   struct DeadlockerClass {
      DeadlockerClass() {
        NSObject* obj = [[NSObject alloc] init];
        [obj performSelectorOnMainThread:@selector(description) withObject:0 waitUntilDone:YES];
      }
   };
   static DeadlockerClass deadlocker;
}

int main(int argc, char *argv[])
{
   pthread_t thread = 0;
   pthread_create(&thread,0,ThreadFunction,0);
   return NSApplicationMain(argc,  (const char **) argv);
}

It deadlocks because 'deadlocker' SL will first take the shared locks guarding SLs, then it waits for the event loop to run (performSelectorOnMainThread). Apple's code in NSApplicationMain setup part also uses SLs, so they'll wait for the shared lock guarding SLs which is already taken by 'deadlocker'.

What is the suggested strategy for avoiding such problems? (Other than don't use static locals, or use -fno-threadsafe-statics compiler option)

Regards,
Miklós








 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/xcode-users/email@hidden

This email sent to email@hidden



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.