C++ static locals share a global mutex? - deadlock issue
C++ static locals share a global mutex? - deadlock issue
- Subject: C++ static locals share a global mutex? - deadlock issue
- From: "Miklós Fazekas" <email@hidden>
- Date: Wed, 30 Jan 2008 10:50:22 +0100
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:
This email sent to email@hidden