Data race with Singleton in thread sanitizer

Hi,


when I run my iOS app with thread sanitizer enabled I get tons of data race warnings when accessing an singleton:


+ (SessionContext *)sharedSessionContext { 
    static SessionContext *sharedInstance = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedInstance = [[SessionContext alloc] initSingleton];
    });
    return sharedInstance;
}


I can't spot the difference of the code above to the proposed pattern from WWDC 2016 session 412 (besides the usage of a function instead of a class function):


Singleton *getSingleton() {
     static dispatch_once_t predicate;
     dispatch_once(&predicate, ^{ 
          sharedInstance = [[self alloc] init];
      });
     return sharedInstance;
}

Error log:


file:///Sources/***/Common/Context/SessionContext.m: runtime: Threading Issues: Data race in +[SessionContext sharedSessionContext] at __llvm_gcov_ctr.2583


notice: Threading Issues: '__llvm_gcov_ctr.2583' is a global variable (0x10db63af8)


Write of size 8 by thread 4

#0 0x0000000108155267 in +[SessionContext sharedSessionContext] at /Sources/***/Common/Context/SessionContext.m:157

#1 0x0000000107504b05 in __43-[LogonController loadData:]_block_invoke at /Sources/***//LogonController:288

#2 0x00000001100d589c in __tsan::invoke_and_release_block(void*) ()

#3 0x000000011aa9edb5 in _dispatch_client_callout ()

Write of size 8 by thread 15

#0 0x0000000108155267 in +[SessionContext sharedSessionContext] at Sources/***/Common/Context/SessionContext.m:157

#1 0x000000010688aa84 in -[TitleView loadLogoLoggedIn] at /Sources/***/TitleView.m:260


… Data race in +[SessionContext sharedSessionContext] at __llvm_gcov_ctr.2583

Do you have code coverage enabled? I’ve never tried combining that with TSan but it seems like a bad idea (-:

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Spot on - the memory modification race conditions are due to the generated coverage information

Thanks,

Thomas

Data race with Singleton in thread sanitizer
 
 
Q