作者:朱金灿
在并发访问sqlite数据库会出现这样一个错误:databseis locked,这是sqlite数据库对并发支持不太好的缘故造成的。采用网上的一种的思路是通过互斥信号量来达到并发访问的目的。下面是一个跨平台的互斥信号量类:
//ProcessMutex.h文件:
#ifndef __PROCESS_MUTEX_H__
#define __PROCESS_MUTEX_H__
#if defined _WIN32 || defined _WIN64
#include <Windows.h>
#endif
#ifdef linux
#include <unistd.h>
#include <semaphore.h>
#include <stdio.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <memory.h>
#endif
class CProcessMutex
{
public:
/* 默认创建匿名的互斥 */
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()
{
//互斥锁创建失败
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 %d\n", 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); // 执行sqlite的相关操作
pMutex.UnLock();