我正在使用C语言编写函数库,它提供了读取,写入和清理sqlite3数据库表的寄存器的基本函数。
当我用一个终端执行它时,所有功能都正常工作。但是,我的问题是当我尝试使用多个终端的功能时。例如,在一个终端中,我有一个程序,它使用一个函数将信息存储在数据库文件的表中。另一方面,在另一个终端中,我有一个程序,它使用不同的功能,将信息存储在同一数据库的另一个表中。然后,在此环境中,信息无法正确存储。所以,我认为我必须使用信号量或互斥量机制来实现所有函数。
在sqlite3文档中搜索,我发现有些函数提供了互斥机制。这些功能如下:
我已经尝试了我的功能,但结果是一样的,当我尝试使用不同的进程存储信息(在同一个数据库中写入)时,信息无法正确存储。我为存储信息的两个函数实现的代码更简单,如下所示:
第一个函数=>将数据存储在table1中。
int add_register_table1(unsigned short int type,unsigned short int err, const char *msg, const char *agent)
{
//Local variables:
int rc, t0;
char buffer[BUFFER_SIZE];
char *errMsg = 0;
sqlite3 *db;
sqlite3_mutex* mutex;
//Initializing variables:
t0 = (int) time(NULL); //Save the current time in seconds
//Opening the syslog.db database connection:
rc = sqlite3_open(database.db, &db);
if(rc != SQLITE_OK) //Error checking
return ERROR;
mutex = sqlite3_db_mutex(db); //Acquire the mutex
//Writing data:
sqlite3_mutex_enter(mutex); //Enter critical zone
sprintf (buffer,"INSERT INTO table1 VALUES ('%d','%d','%d','%s','%s');", t0, type, err,
msg, agent);
rc = sqlite3_exec(db, buffer, NULL, NULL, &errMsg);
sqlite3_mutex_leave(mutex); //Leave critical zone
if(rc != SQLITE_OK) //Error checking
return ERROR;
//Closing the database connection:
sqlite3_close(db);
return NOERROR;
}
第二个函数,它是相同的,但它将信息存储在同一个数据库文件中的另一个表中:
int add_register_table2(unsigned short int type,unsigned short int err, const char *msg, const char *agent)
{
//Local variables:
int rc, t0;
char buffer[BUFFER_SIZE];
char *errMsg = 0;
sqlite3 *db;
sqlite3_mutex* mutex;
//Initializing variables:
t0 = (int) time(NULL); //Save the current time in seconds
//Opening the syslog.db database connection:
rc = sqlite3_open(database.db, &db);
if(rc != SQLITE_OK) //Error checking
return ERROR;
mutex = sqlite3_db_mutex(db); //Acquire the mutex
//Writing data:
sqlite3_mutex_enter(mutex); //Enter critical zone
sprintf (buffer,"INSERT INTO table2 VALUES ('%d','%d','%d','%s','%s');", t0, type, err,
msg, agent);
rc = sqlite3_exec(db, buffer, NULL, NULL, &errMsg);
sqlite3_mutex_leave(mutex); //Leave critical zone
if(rc != SQLITE_OK) //Error checking
return ERROR;
//Closing the database connection:
sqlite3_close(db);
return NOERROR;
}
我的问题如下:
·查看我的C代码,使用的sqlite3互斥函数使用得很好,必须正常运行,或者我的代码中的实现是错误的?
·是否有任何其他类型的机制来实现具有多个进程的并发性的写入/读取数据库?哪些是这些机制以及如何实现它?
我几天前就遇到过这个问题,但我找不到解决办法。
非常感谢!