多线程同步操作数据库

#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);

}

总结:多线程同步操作数据库时,容易出现操作数据库失败,内存泄露,甚至会导致程序崩溃,解决方法是增加互斥锁,确保同一时刻只有一个线程去操作数据库,其他线程排队等待操作,以上程序测试通过。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值