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]) {
}
}
- (void)method2FromClass2 {
@synchronized ([Application submitChangesLock]) {
}
}
, , - , , , , , , , , , , .
: , .
EDIT:
@synchronized performSelectorOnMainThread: waitUntilDone:
- (void)writeToDatabase {
}
- (void)method2FromClass2 {
[self performSelectorOnMainThread:@selector(writeToDatabase) withObject:nil waitUntilDone:YES];
}
, , .
.