`
softwarexiang120
  • 浏览: 37721 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

SQLite3并发时报database locked

阅读更多

sqlite3数据库是一个数据库一个文件,所以当多进程访问操作同一数据库时,即与操作同一文件一样,文件锁问题。
对同个数据库进行多进程同时读是允许的,但多进程同时写是不允许的,如果一个进程已经正在写,其他进程就会写失败。sqlite3返回信息就是"Database is locked",错误码SQLITE_BUSY。

1、解决方法一
官方网站对这个问题是这个说的:
When SQLite tries to access a file that is locked by another process, the default behavior is to return SQLITE_BUSY. You can adjust this behavior from C code using the sqlite3_busy_handler() or sqlite3_busy_timeout() API functions.
建议用sqlite3_busy_handler()或sqlite3_busy_timeout()在执行业务代码中加入相应的行为。

int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
int sqlite3_busy_timeout(sqlite3*, int ms);
两个函数只能用一个,用了一个,另一个就失效了。

2、解决方法二
加上一个循环判断。
while( 1 )
{
    if( SQLITE_OK != sqlite3_exec( myconn, sql, 0, 0, &m_sqlerr_msg) )
    {
        if( strstr(m_sqlerr_msg, "database is locked") )
        {
            sleep(1);
            continue;
        }
        break;
    }
}
3、解决方法三
用信号量做PV操作
sem_p(semid,0);
sqlite3_exec( myconn, sql, 0, 0, &m_sqlerr_msg);
sem_v(semid,0);

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics