测试在多线程下操作sqlite内存数据库(转)

本文通过测试展示了在SQLite 3.5.7版本中,如何在一个主线程内创建内存数据库并进行表的创建,随后在两个子线程中对该数据库进行并发插入操作。测试结果表明,自3.3.1版本开始,SQLite支持多线程操作同一数据库句柄。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


硬件平台: Linux on vmware6
操作系统:Trustix Linux3
SQLITE: sqlite-3.5.7


以下摘自:http://www.sqlite.org/c3ref/open.html
int sqlite3_open(
const char *filename, /* Database filename (UTF-8) */
sqlite3 **ppDb /* OUT: SQLite db handle */
);

If the filename is ":memory:", then an private in-memory database is created for the connection. This in-memory database will vanish when the database connection is closed. Future version of SQLite might make use of additional special filenames that begin with the ":" character. It is recommended that when a database filename really does begin with ":" that you prefix the filename with a pathname like "./" to avoid ambiguity.


我在主线程中使用
int sqlitehandle = sqlite3_open(":memory:", &pdb);
创建内存数据库,并创建表:
int rs = sqlite3_exec(pdb, "CREATE TABLE testtbl(id int NOT NULL, name varchar(100))", 0, 0,0);


然后创建两个新的线程,将pdb传入线程中,主线程进入睡眠。
在两个线程中,均执行:
  while(1)
  {
    int rs = sqlite3_exec(pdb, "INSERT INTO testtbl values(25,'aaaaaaaaaaaa')", 0,0,0);
    printf("rs = %d/n", rs);
    if(rs != SQLITE_OK)
    {
        printf("err rs=%d/n", rs);
        break;
    }
    usleep(10);
 }

测试结果显示是可以两个线程操作同一个句柄的!!!
并且在程序运行时,我用lsof命令查看该进程的句柄状态,确实没有任何磁盘的操作!!!

但有个问题不知道是否是由于我是虚拟机引起,即该程序在执行(约1分钟后),两个线程像是进入死锁状态,再没有任何动作,没有退出,也没有显示insert失败!这暂时不理解。


 
文件:sqlite-3.5.7.tar.gz
大小:2506KB
下载:下载



2008.5.5增加:

根据sqlite3的描述,自3.3.1版本起才能在多个线程中操作同一个句柄.但未测试;

另外,上面的例子中,如果不是内存数据库,那么多个线程同时写同一个句柄,sqlite_exec会返回21的错误,这说明了需要在写前加锁.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值