SQLite3 和多个进程

SQLite3 and multiple processes(SQLite3 和多个进程)
本文介绍了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,请将您的 write 事务包装在 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.

您还可以使用操作系统级别的同步来获取数据库的互斥锁,或者使用操作系统级别的线程间/进程间消息传递在一个线程完成访问数据库时发出信号.

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 和多个进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL to Generate Periodic Snapshots from Transactions Table(用于从事务表生成定期快照的SQL)