I use FMDB to work with my database, which works great. The application uses a background thread that does some work and needs access to the database. At the same time, the main thread must run some queries in the same database. FMDB itself has a small locking system, however I added one more of my classes.
Each query is only executed if my class indicates that the database is not in use. After completing the actions, the database is unlocked. This works as expected until the load is too high. When I access a lot of data with a thread running in the main thread, an EXC_BAD_ACCESS error occurs.
Here it looks:
- (BOOL)isDatabaseLocked { return isDatabaseLocked; } - (Pile *)lockDatabase { isDatabaseLocked = YES; return self; } - (FMDatabase *)lockedDatabase { @synchronized(self) { while ([self isDatabaseLocked]) { usleep(20); //NSLog(@"Waiting until database gets unlocked..."); } isDatabaseLocked = YES; return self.database; } } - (Pile *)unlockDatabase { isDatabaseLocked = NO; return self; }
Debugger says error occurs when [FMResultSet next] in line
rc = sqlite3_step(statement.statement);
I double-checked all hold values ββand all objects exist at this time. Again, this only happens when the main thread launches a lot of requests while the background thread is running (which always creates a lot of load). The error is always generated by the main thread, not the background thread.
My last idea would be that both threads simultaneously start lockDatabase so that they can get the database object. So I added a mutex lock through "@synchronized (self)". However, this did not help.
Does anyone have a key?
sqlite objective-c iphone exc-bad-access fmdb
danielkbx
source share