SQLite WAL模式,在多个线程中具有多个事务

前端之家收集整理的这篇文章主要介绍了SQLite WAL模式,在多个线程中具有多个事务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在WAL模式下,sqlite可以在同一个数据库上同时拥有多个事务吗?

下面是一个示例应用程序,它生成500个线程,每个线程创建一个新的sqlite连接.插入数据发生在事务中.

在此示例应用中:

#include "sqlite3.h"
#include "nspr\prthread.h"

void CreateThreads();
static void StartThread(void *Arg);

int main()
{
    CreateThreads();
}

void CreateThreads()
{
    for(int i = 0; i<500;i++)
    {
        PR_CreateThread(PR_USER_THREAD,StartThread,NULL,PR_PRIORITY_NORMAL,PR_GLOBAL_THREAD,PR_UNJOINABLE_THREAD,0);
    }
    Sleep(10000);
}

void StartThread(void *Arg)
{
    sqlite3 *sqlite;
    char *errmsg;
    const char *err;
    const char *unused;
    int ret;
    const unsigned char * journal;
    const char *dir = "D:\\Samples\\test.sqlite";
    ret = sqlite3_open(dir,&sqlite);
    if(ret != sqlITE_OK)
    {
       err = sqlite3_errmsg(sqlite);
         return;
    }

    char query[100];
    strcpy(query,"Begin transaction");
    if(sqlite3_exec(sqlite,query,&errmsg) != sqlITE_OK )
    {
        printf("%s",errmsg);
        return;
    }

    strcpy(query,"insert into test values(1,2,3,4,5,6)");
    for(int i = 0; i<10;i++)
    {
        if(sqlite3_exec(sqlite,&errmsg) != sqlITE_OK )
        {
         printf("%s",errmsg);
            return;
        }
    }

    strcpy(query,"End Transaction");
    if(sqlite3_exec(sqlite,errmsg);
        return;
    }
    return;
}

我得到’数据库被锁定’运行它.

我的问题是在WAL模式下我们可以同时进行多笔交易吗?如果是这样,我在示例应用程序中缺少什么?

解决方法

无论如何,sqlite在其当前版本中不支持并发写入.可以同时有多个读者进程,但最多只有一个编写者. (见 FAQ entry #5

启用“预写日志记录”后,该事实不会发生变化. WAL实现更多并发:

WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently.

但不写并发:

Writers merely append new content to the end of the WAL file. Because writers do nothing that would interfere with the actions of readers,writers and readers can run at the same time. However,since there is only one WAL file,there can only be one writer at a time.

(以上摘自the documentation on WAL.)

猜你在找的Sqlite相关文章