我有一个 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;
}
最佳答案
联系了 SQLite 团队:这是他们的回复-
当你关闭一个连接时(在WAL
模式下),
SQLite 检查进程中是否有任何其他连接正在占用
正在关闭的数据库文件上的 POSIX 锁。如果是这样,则推迟
关闭文件句柄,直到另一个连接断开它的连接
POSIX 锁(如果还有另一个文件描述符将被重用)
打开到同一文件的连接,但否则它只是
一直等待,直到可以安全关闭)。
结论是: 所以直到从 main() 函数关闭连接 从其他线程打开的句柄不会被关闭!
关于c++ - SQLite:以 WAL 模式保留文件句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10332253/