SQLite:在 WAL 模式下持久化文件句柄

SQLite: Persisting file handles in WAL mode

本文关键字:持久化 文件句柄 模式 WAL SQLite      更新时间:2023-10-16

我有一个C++程序,其中有多个线程写入单个数据库的SQLite表(启用了WAL模式)。每个线程创建一个 SQLite 句柄,执行 sqlite3_open(),写入表(事务中有写入),然后执行 sqlite3_close(),然后删除 SQLite 句柄。然后线程死亡。

即使在所有线程死亡后,SQLite 句柄仍然处于打开状态。为什么 SQLite 句柄没有关闭?我在这里错过了什么?

我的C++程序运行在 CentOS 5.5 上。

[编辑]这是我使用的示例程序pthread

void threadFunction(void* pArg) {
    sqlite3 *handle;
    sqlite3_open("a.cm", &handle);    
    printf("Worker thread - Opened n");
    sleep(10);    
    int r = sqlite3_close(handle);
    printf("Ret: %dn", r);
    printf("Worker thread - Closed n");
}
int main() {
    int i(0);
    pthread_t thread1, thread2;
    printf("Creating a worker threadn");
    printf("SQLite libversion: %sn", sqlite3_libversion());
    sqlite3 *handle;
    sqlite3_open("a.cm", &handle);    
    sqlite3_exec(handle, "pragma journal_mode = WAL", NULL, NULL, NULL);    
    printf("Main thread - Opened n");
    pthread_create(&thread1, NULL, threadFunction, NULL);
    pthread_create(&thread2, NULL, threadFunction, NULL);
    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);
    sleep(200);
    sqlite3_close(handle);
    printf("Main thread - close n");
    return 0;
}

联系了SQLite团队:这是他们的回复-

关闭一个连接(在WAL模式下)时,SQLite 检查进程中是否有任何其他连接保持正在关闭的数据库文件上的 POSIX 锁。如果是这样,它会推迟关闭文件句柄,直到另一个连接丢弃其POSIX 锁(如果还有另一个,文件描述符将被重用打开与同一文件的连接,但除此之外,它只是徘徊,直到可以安全关闭)。

结论是:所以直到从main()函数关闭连接从其他线程打开的句柄将不会关闭!