您的位置:首页 > 数据库

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

2008-11-13 18:50 288 查看
[/b]
硬件平台: 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的错误,这说明了需要在写前加锁.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: