A mutex only blocks the main thread when it reaches its call using the @synchronized directive

I am creating a multi-threaded application from which more than one stream can be written to the sqlite3 database, including the main stream. I declared a static public variable to be used for the mutex:

@implementation Application

#pragma mark -
#pragma mark Static Initializer
static NSString * SubmitChangesLock = nil;

+ (void)initialize {
    [super initialize];
    SubmitChangesLock = [[NSString alloc] initWithString:@"Submit-Changes-Lock"];
}

+ (NSString *)submitChangesLock {
    return SubmitChangesLock;
}

@end

and inside each method that should be written to the database, I use this variable with the @synchronized directive to lock the section that is written to the database.

- (void)method1FromClass1 {
    @synchronized ([Application submitChangesLock]) {
        // write to the database here...
    }
}

- (void)method2FromClass2 {
    @synchronized ([Application submitChangesLock]) {
        // write to the database here...
    }
}

, , - , , , , , , , , , , .

: , .

EDIT: @synchronized performSelectorOnMainThread: waitUntilDone:

- (void)writeToDatabase {
    // write to the database here...
}
- (void)method2FromClass2 {
    [self performSelectorOnMainThread:@selector(writeToDatabase) withObject:nil waitUntilDone:YES];
}

, , .

.

0
1

iOS , , / ​​ .

NSOperationQueue setMaxConcurrentOperationCount: 1, deanWombourne, . (NSInvocationOperation), .

, , , , performSelectorOnMainThread:withObject:waitUntilDone: .

, DB. , -.

+1

All Articles