SQLite 多執行緒序列寫入
阿新 • • 發佈:2019-02-09
確認在 "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("\n\n\n"); wsprintfA(szSQL, "DELETE FROM DemoTable WHERE Thread = 1"); result = sqlite3_exec(m_pSQLite3, szSQL, NULL, NULL, &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, szSQL, NULL, NULL, &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)", NULL, NULL, &errmsg); result = sqlite3_exec(pSQLite, "DELETE FROM DemoTable", NULL, NULL, &errmsg); DemoSQLite demoSQLite(pSQLite); demoSQLite.Start(); Sleep(1000 * 5); demoSQLite.Stop(); sqlite3_close(pSQLite); return 0; }