SQLite3和多个进程 [英] SQLite3 and multiple processes

查看:414
本文介绍了SQLite3和多个进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当多个进程访问一个SQLite数据库文件时,应该如何确保正确性?

How should one ensure correctness when multiple processes access one single SQLite database file?

推荐答案

首先,避免同时访问sqlite数据库文件。并发是sqlite的弱点之一,如果您有一个高度并发的应用程序,请考虑使用另一个数据库引擎。

First, avoid concurrent access to sqlite database files. Concurrency is one of sqlite's weak points and if you have a highly concurrent application, consider using another database engine.

如果无法避免并发或删除sqlite,请包装 BEGIN IMMEDIATE; ... END; 中>写入事务。 sqlite中的默认事务处理模式为 DEFERRED ,这意味着仅在首次实际写入尝试时才获得锁定。使用 IMMEDIATE 事务,将立即获取锁,或者您立即获得 SQLITE_BUSY 。当有人锁定数据库时,其他锁定尝试将导致 SQLITE_BUSY

If you cannot avoid concurrency or drop sqlite, wrap your write transactions in BEGIN IMMEDIATE; ... END;. The default transaction mode in sqlite is DEFERRED which means that a lock is acquired only on first actual write attempt. With IMMEDIATE transactions, the lock is acquired immediately, or you get SQLITE_BUSY immediately. When someone holds a lock to the database, other locking attempts will result in SQLITE_BUSY.

处理 SQLITE_BUSY 是您必须自己决定的事情。对于许多应用程序而言,等待一两秒钟然后重试可以正常工作,在 n 次失败尝试后放弃。有sqlite3 API帮助器可以简化此操作,例如 sqlite3_busy_handler() sqlite3_busy_timeout(),但也可以手动完成。

Dealing with SQLITE_BUSY is something you have to decide for yourself. For many applications, waiting for a second or two and then retrying works quite all right, giving up after n failed attempts. There are sqlite3 API helpers that make this easy, e.g. sqlite3_busy_handler() and sqlite3_busy_timeout() but it can be done manually as well.

您还可以使用OS级同步来获取对数据库的互斥锁,或使用OS级线程间/进程间消息传递来指示何时有一个线程访问数据库。

You could also use OS level synchronization to acquire a mutex lock to the database, or use OS level inter-thread/inter-process messaging to signal when one thread is done accessing the database.

这篇关于SQLite3和多个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆