并發(fā)訪問sqlite數(shù)據(jù)庫出現(xiàn)databse is locked的錯(cuò)誤的一個(gè)解決辦法
作者:朱金燦
來源:http://blog.csdn.net/clever101
???
??????? 在并發(fā)訪問sqlite數(shù)據(jù)庫會(huì)出現(xiàn)這樣一個(gè)錯(cuò)誤:databseis locked,這是sqlite數(shù)據(jù)庫對并發(fā)支持不太好的緣故造成的。采用網(wǎng)上的一種的思路是通過互斥信號量來達(dá)到并發(fā)訪問的目的。下面是一個(gè)跨平臺(tái)的互斥信號量類:
//ProcessMutex.h文件:
#ifndef __PROCESS_MUTEX_H__
#define __PROCESS_MUTEX_H__
#if defined _WIN32 || defined _WIN64
#include
#endif
#ifdef linux
#include
#include
#include
#include
#include
#include
#include
#endif
class CProcessMutex
{
public:
/* 默認(rèn)創(chuàng)建匿名的互斥 */
CProcessMutex(const char* name = NULL);
~CProcessMutex();
bool Lock();
bool UnLock();
private:
#if defined _WIN32 || defined _WIN64
void* m_pMutex;
#endif
#ifdef linux
set_t* m_pSem;
#ednif
char m_cMutexName[30];
};
#endif
//ProcessMutex.cpp文件:
#include "ProcessMutex.h"
#if defined _WIN32 || defined _WIN64
CProcessMutex::CProcessMutex(const char* name)
{
memset(m_cMutexName, 0 ,sizeof(m_cMutexName));
int min = strlen(name)>(sizeof(m_cMutexName)-1)?(sizeof(m_cMutexName)-1):strlen(name);
strncpy(m_cMutexName, name, min);
m_pMutex = CreateMutex(NULL, false, m_cMutexName);
}
CProcessMutex::~CProcessMutex()
{
CloseHandle(m_pMutex);
}
bool CProcessMutex::Lock()
{
//互斥鎖創(chuàng)建失敗
if (NULL == m_pMutex)
{
return false;
}
DWORD nRet = WaitForSingleObject(m_pMutex, INFINITE);
if (nRet != WAIT_OBJECT_0)
{
return false;
}
return true;
}
bool CProcessMutex::UnLock()
{
return ReleaseMutex(m_pMutex);
}
#endif
#ifdef linux
CProcessMutex::CProcessMutex(const char* name)
{
memset(m_cMutexName, 0 ,sizeof(m_cMutexName));
int min = strlen(name)>(sizeof(m_cMutexName)-1)?(sizeof(m_cMutexName)-1):strlen(name);
strncpy(m_cMutexName, name, min);
m_pSem = sem_open(name, O_CREAT, 0644, 1);
}
CProcessMutex::~CProcessMutex()
{
int ret = sem_close(m_pSem);
if (0 != ret)
{
printf("sem_close error %dn", ret);
}
sem_unlink(m_cMutexName);
}
bool CProcessMutex::Lock()
{
int ret = sem_wait(m_pSem);
if (ret != 0)
{
return false;
}
return true;
}
bool CProcessMutex::UnLock()
{
int ret = sem_post(m_pSem);
if (ret != 0)
{
return false;
}
return true;
}
#endif
使用示例代碼如下:
CProcessMutex pMutex("MutexName");
pMutex.Lock();
sqlite3_exec( myconn, sql, 0, 0, &m_sqlerr_msg); // 執(zhí)行sqlite的相關(guān)操作
pMutex.UnLock();
參考文獻(xiàn):
?
1. 多進(jìn)程之間的互斥信號量的實(shí)現(xiàn)(Linux和windows跨平臺(tái))
?
2.sqlite遇到database is locked問題的完美解決