#include <sys/types.h>
#include <sys/socket.h>
#include <linux/in.h>
#include <linux/un.h>
#include <string.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <errno.h>
#include <unistd.h>
#include <unistd.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include "sqlite3.h"
#include <sys/time.h>
#include <math.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <termios.h>
#include "eventlog.h"
//****************db lock
pthread_mutex_t *foreventdb;
void SendToEventLogDb(int type,float value,long int ts)
{
pthread_mutex_lock(foreventdb);
switch(type)
{
case 10 : SaveToEventLogDb(type,value,ts);break;
case 20 : SaveToEventLogDb(type,value,ts);break;
default : break;
}
printf("start unlock!\n");
pthread_mutex_unlock(foreventdb);
printf("end unlock!\n");
}
void * sqlite_ser_thread()
{
while(1)
{
sleep(1);
SendToEventLogDb(10,10.1,10);
printf("save 11111111 success!\n");
}
}
void * save_ser_thread()
{
while(1)
{
sleep(1);
SendToEventLogDb(20,20.2,20);
printf("save 22222222 success!\n");
}
}
static void pqm_db_init()
{
InitEventLogDb();
}
void main()
{
pthread_t sqlite_thread,save_thread;
foreventdb=malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(foreventdb,NULL);
pqm_db_init();
pthread_create(&sqlite_thread, NULL, sqlite_ser_thread, NULL);
pthread_create(&save_thread, NULL, save_ser_thread, NULL);
pthread_join(sqlite_thread,NULL);
}
總結:
多線程同步操作數據庫時,容易出現操作數據庫失敗,內存泄露,甚至會導致程序崩潰,解決方法是增加互斥鎖,確保同一時刻只有一個線程去操作數據庫,其他線程排隊等待操作,以上程序測試通過。