加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SQLite学习(五) - 异步I/O的实现 sqlite3async.c

发布时间:2020-12-12 20:15:52 所属栏目:百科 来源:网络整理
导读:一般情况下,当我们的程序有 I/O 操作需要写磁盘时,程序会等待 I/O 完成后才把程序控制还给用户。由于 I/O 是相对比较慢的,所以这有可能会成为性能瓶颈。 SQLite 的异步 I/O 使用一个单独的线程完成 I/O 。 虽然这样没有减少系统资源的使用,但是控制权立

一般情况下,当我们的程序有I/O操作需要写磁盘时,程序会等待I/O完成后才把程序控制还给用户。由于I/O是相对比较慢的,所以这有可能会成为性能瓶颈。SQLite的异步I/O使用一个单独的线程完成I/O虽然这样没有减少系统资源的使用,但是控制权立刻返回给用户,更好的用户体验。


1.数据库ACID中的D
使用异步
I/O带来的一个问题就是失去了数据库的持久性(Durable)特性。由于I/O在后台进行,你不知道什么时候I/O会完成。如果在I/O完成之前系统出现错误,后面的用户将看不到之前的改动。

2. SQLIte的异步IO怎么工作的?
(1)创建一个VFS_Object
(2)sqlite3_vfs_register()注册这个Object
(3)SQLitevfs_xwrite()进行I/O操作时,不是直接写到磁盘,而是写到write-queue,等待后台进程来完成I/O
(4)SQLite执行读取操作时,用vfx_xread(),会同时从磁盘和write-queue读取,这样看上去就好像write-queue已经写到磁盘上了
(5) asynchronous I/O VFS is registered by calls sqlite3async_initialize() and sqlite3async_shutdown().

SQLite异步I/O限制
SQLite异步I/O实现较简单。比如如果有大量的数据写入write-queue,超出了后台write线程的处理能力,write-queue将无限制的长大,这样可能导致系统out-of-memory

3.锁和并发
文件锁默认是打开的,当一个数据库连接开始一个transaction,会立即获得文件锁,transaction结束(commitRollback)也不会释放锁,只有当“write-queue”为空时才释放锁。

可以用sqlite3async_control() disable文件锁,这样I/O时就不需要额外的去获得文件锁,以得到更好的性能。

4.编译和使用Asynchronous IO extension
异步I/O的代码在C源文件sqlite3async.c,sqlite3async.h (目录/ext/anysnc)中。

The asynchronous IO VFS API is described in detail in comments in sqlite3async.h. Using the API usually consists of the following steps:

1. Register the asynchronous IO VFS with SQLite by calling the sqlite3async_initialize() function.
2.Create a background thread to perform write operations and call sqlite3async_run().
3.Use the normal SQLite API to read and write to databases via the asynchronous IO VFS.

Refer to comments in the sqlite3async.h header file for details.

5.移植
现在Asynchronous IO extension支持平台有win32系统,支持pthreads interface的系统Mac OS X,Linux,and other varieties of Unix要移植Asynchronous IO extension到其他平台,需要实现mutex and condition variable primitives.

Currently there is no externally available interface to allow this,but modifying the code within sqlite3async.c to include the new platforms concurrency primitives is relatively easy. Search within sqlite3async.c for the comment string "PORTING FUNCTIONS" for details. Then implement new versions of each of the following:

static void async_mutex_enter(int eMutex); static void async_mutex_leave(int eMutex); static void async_cond_

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读