2

我有一个 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: %d\n", r);
    printf("Worker thread - Closed \n");
}

int main() {
    int i(0);
    pthread_t thread1, thread2;
    printf("Creating a worker thread\n");
    printf("SQLite libversion: %s\n", 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;
}
4

1 回答 1

4

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

当您关闭一个连接(在WAL模式下)时,SQLite 会检查进程中的任何其他连接是否持有正在关闭的数据库文件的 POSIX 锁。如果是这样,它会推迟关闭文件句柄,直到另一个连接放弃其 POSIX 锁(如果打开同一个文件的另一个连接,文件描述符将被重用,否则它只是等待直到可以安全关闭) .

结论是:因此,在从 main() 函数关闭连接之前,从其他线程打开的句柄不会关闭!

于 2012-04-30T04:54:12.557 回答