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