Skip to content

Commit

Permalink
[bugfix] 还是需要加锁,使用 pthread_mutex_t 避免线程优先级反转
Browse files Browse the repository at this point in the history
  • Loading branch information
lijianghuai committed Jun 19, 2024
1 parent f0de63b commit f7cf50d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 2 additions & 2 deletions LKDBHelper.podspec.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "LKDBHelper",
"version": "2.6.2",
"version": "2.6.3",
"summary": "全自动的插入,查询,更新,删除, an automatic database operation thread-safe and not afraid of recursive deadlock",
"description": "全面支持 NSArray,NSDictionary, ModelClass, NSNumber, NSString, NSDate, NSData, UIColor, UIImage, CGRect, CGPoint, CGSize, NSRange, int,char,float, double, long.. 等属性的自动化操作(插入和查询)",
"homepage": "https://github.com/li6185377/LKDBHelper-SQLite-ORM",
Expand All @@ -10,7 +10,7 @@
},
"source": {
"git": "https://github.com/li6185377/LKDBHelper-SQLite-ORM.git",
"tag": "2.6.2"
"tag": "2.6.3"
},
"platforms": {
"ios": "11.0",
Expand Down
7 changes: 7 additions & 0 deletions LKDBHelper/Helper/LKDBHelper.m
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#import "LKDBHelper.h"
#import <sqlite3.h>
#import <pthread/pthread.h>

#ifndef SQLITE_OPEN_FILEPROTECTION_NONE
#define SQLITE_OPEN_FILEPROTECTION_NONE 0x00400000
Expand Down Expand Up @@ -340,6 +341,7 @@ - (void)runAutoVacuumAction {
// 读取全局缓存文件
static NSMutableDictionary *dbAutoVaccumMap = nil;
static NSString *dbAutoVaccumPath = nil;
static pthread_mutex_t dbLock;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *cacheDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
Expand All @@ -348,24 +350,29 @@ - (void)runAutoVacuumAction {
if (!dbAutoVaccumMap) {
dbAutoVaccumMap = [NSMutableDictionary dictionary];
}
pthread_mutex_init(&dbLock, NULL);
});
// 3天操作一次
NSString *dbKey = self.dbPath.lastPathComponent;
pthread_mutex_lock(&dbLock);
NSInteger lastTime = [[dbAutoVaccumMap objectForKey:dbKey] integerValue];
if (0 == lastTime) {
// 记录第一次运行的时间
lastTime = nowTime;
[dbAutoVaccumMap setObject:@(nowTime) forKey:dbKey];
[dbAutoVaccumMap writeToFile:dbAutoVaccumPath atomically:YES];
}
pthread_mutex_unlock(&dbLock);
if (nowTime - lastTime < 259200) { // 60 * 60 * 24 * 3
return;
}
// 执行数据压缩
[self executeSQL:@"vacuum" arguments:nil];
// 记录执行时间
pthread_mutex_lock(&dbLock);
[dbAutoVaccumMap setObject:@(nowTime) forKey:dbKey];
[dbAutoVaccumMap writeToFile:dbAutoVaccumPath atomically:YES];
pthread_mutex_unlock(&dbLock);
}

- (BOOL)executeSQL:(NSString *)sql arguments:(NSArray *)args {
Expand Down

0 comments on commit f7cf50d

Please sign in to comment.