加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SQLite 多线程串行写入

发布时间:2020-12-12 20:28:19 所属栏目:百科 来源:网络整理
导读:确认在 "SQLite3.c" 中,宏 SQLITE_THREADSAFE = 1 或者 2 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */ #include "Thread.h"extern "C"{ #include "SQLite3.h"};#include stdio.h#include "Utility.h"//////////////////////////////////////////

确认在 "SQLite3.c" 中,宏 SQLITE_THREADSAFE = 1 或者 2
# define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */

#include "Thread.h"

extern "C"
{
 #include "SQLite3.h"
};

#include <stdio.h>

#include "Utility.h"

//////////////////////////////////////////////////////////////////////////

int Print(void *pParam,int argc,char ** argv,char ** szColName)
{
 for (int i=0; i<argc; ++i) {
  printf("%s - %s,",szColName[i],argv[i]);
 }
 printf("n");
 return 0;
}

//////////////////////////////////////////////////////////////////////////

class DemoSQLite
{
 typedef ThreadT<DemoSQLite> CThread;

public:
 DemoSQLite(sqlite3 *pSQLite3)
  : m_pSQLite3(pSQLite3)
 {
  m_lThreadCount = 0;

  m_threadRead.owner(this);
  m_threadWrite.owner(this);
 }

 VOID Start()
 {
  m_threadRead.Start(1);
  m_threadWrite.Start(4);
 }
 VOID Stop()
 {
  m_threadRead.Stop();
  m_threadWrite.Stop();
 }

 VOID Svc(CThread *pThread,HANDLE hExit)
 {
  char *errmsg= NULL;
  int result = 0;

  if (pThread == &m_threadRead) {
   CHAR szSQL[128] = { 0 };
   while (TRUE) {
    if (WaitForSingleObject(hExit,1000) == WAIT_OBJECT_0) {
     break;
    }

    wsprintfA(szSQL,"SELECT * FROM DemoTable WHERE Thread = 1");
    result = sqlite3_exec(m_pSQLite3,szSQL,Print,NULL,&errmsg);

    printf("nnn");

    wsprintfA(szSQL,"DELETE FROM DemoTable WHERE Thread = 1");
    result = sqlite3_exec(m_pSQLite3,&errmsg);
   }
  }
  if (pThread == &m_threadWrite) {
   LONG lThread= InterlockedIncrement(&m_lThreadCount);
   LONG lCount = 0;

   CHAR szSQL[128] = { 0 };
   while (TRUE) {
    if (WaitForSingleObject(hExit,1) == WAIT_OBJECT_0) {
     break;
    }

    wsprintfA(szSQL,"INSERT INTO DemoTable VALUES(%d,%d)",lThread,lCount++);
    result = sqlite3_exec(m_pSQLite3,&errmsg);
   }
  }
 }

private:
 sqlite3 *m_pSQLite3;
 LONG m_lThreadCount;

 CThread m_threadRead;
 CThread m_threadWrite;
};

//////////////////////////////////////////////////////////////////////////

int main()
{
 sqlite3_config(SQLITE_CONFIG_SERIALIZED);

 char *errmsg = NULL;
 sqlite3 *pSQLite= NULL;

 int result = OpenDatabase<0>(".DemoSQLite.db",pSQLite);
 if (result != SQLITE_OK) {
  return -1;
 }
 result = sqlite3_exec(pSQLite,"CREATE TABLE IF NOT EXISTS DemoTable(Thread INTEGER,Count INTEGER)",&errmsg);
 result = sqlite3_exec(pSQLite,"DELETE FROM DemoTable",&errmsg);

 DemoSQLite demoSQLite(pSQLite);
 demoSQLite.Start();
 Sleep(1000 * 5);

 demoSQLite.Stop();
 sqlite3_close(pSQLite);
 return 0;
}


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读