1。使用进程或线程间的同步机制以避免同时操作;如用信号量,互斥锁等(pthread_mutex_lock,pthread_mutex_unlock),如果你的项目工程较大要求较高的话建议用此方法自行封装函数处理同步
2。使用sqlite提供的两个busy handler函数,但对于一个连接来说,只能有一个busy handle,两个函数会相互影响,设置一个的同时会清除另一个,应根据需要来选择。
int sqlite3_busy_handler(sqlite3 *,int (*)(void *,int),void *)
不注册此函数时默认回调函数为NULL,清除busy handle,申请不到锁直接返回;
函数可以定义一个回调函数,当出现数据库忙时sqlite会调用该函数进行延时并返回非0会重试本次操作,回调函数的第二个参数会被传递为此次因BUSY忙事件而调用该函数的次数,因此你完全可以自行控制多少次后(也就是延时多少后)才真正返回BUSY;
回调函数返回非0,数据库会重试当前操作,返回0则当前操作返回sqlITE_BUSY;
int sqlite3_busy_timeout(sqlite3*,int ms);
不注册此函数时默认超时等待为0,当ms<=0时,清除busy handle,申请不到锁直接返回;
定义一个毫秒数,当未到达该毫秒数时,sqlite会sleep并重试当前操作,
如果超过ms毫秒,仍然申请不到需要的锁,当前操作返回sqlITE_BUSY;
很多人用这个函数没有成功,其实只要你仔细查看sqlite的源码就会发现,
这个函数实际上注册了一个默认的sqlite3_busy_handler(sqliteDefaultBusyCallback),而这个回调函数在你的编译环境下可能使得第二个ms参数必需要大于1000且是他的整数倍才有意义,由于此默认callback函数延时较大,建议自己写回调函数然后用slite3_busy_handler注册,这样就可以自己用自己的延时函数或方法进行处理了.
- 附:===================================================================
- staticintsqliteDefaultBusyCallback(
- void*ptr,/*Databaseconnection*/
- intcount/*Numberoftimestablehasbeenbusy*/
- )
- {
- #ifsqlITE_OS_WIN||(defined(HAVE_USLEEP)&&HAVE_USLEEP)
- staticconstu8delays[]=
- {1,2,5,10,15,20,25,50,100};
- staticconstu8totals[]=
- {0,1,3,8,18,33,53,78,103,128,178,228};
- #defineNDELAY(sizeof(delays)/sizeof(delays[0]))
- sqlite3*db=(sqlite3*)ptr;
- inttimeout=db->busyTimeout;
- intdelay,prior;
- assert(count>=0);
- if(count<NDELAY){
- delay=delays[count];
- prior=totals[count];
- }else{
- delay=delays[NDELAY-1];
- prior=totals[NDELAY-1]+delay*(count-(NDELAY-1));
- }
- if(prior+delay>timeout){
- delay=timeout-prior;
- if(delay<=0)return0;
- }
- sqlite3OsSleep(db->pVfs,delay*1000);
- return1;
- #else
- sqlite3*db=(sqlite3*)ptr;
- inttimeout=((sqlite3*)ptr)->busyTimeout;
- if((count+1)*1000>timeout){
- return0;//1000>timeout,sotimeoutmustbiggerthan1000
- }
- sqlite3OsSleep(db->pVfs,1000000);//1000ms
- return1;
- #endif
- }
- intsqlite3_busy_timeout(sqlite3*db,intms){
- if(ms>0){
- db->busyTimeout=ms;
- sqlite3_busy_handler(db,sqliteDefaultBusyCallback,(void*)db);
- }else{
- sqlite3_busy_handler(db,0,0);
- }
- returnsqlITE_OK;
- }
3、解决方法二
加上一个循环判断。