私は、sqlite3データベーステーブルのレジスタを読み取り、書き込み、および消去するための基本的な機能を提供するC言語で関数ライブラリを作成しています。
1つの端末で実行すると、すべての機能が正常に動作します。しかし、私の問題は、複数の端末から機能を使用しようとするときです。たとえば、1 つの端末に、データベース ファイルのテーブルに情報を格納する関数を使用するプログラムがあります。一方、別の端末には、同じデータベースの別のテーブルに情報を格納する別の関数を使用するプログラムがあります。そして、この環境では情報が正しく保存されません。したがって、すべての機能をセマフォまたはミューテックスのメカニズムで実装する必要があると思います。
sqlite3 のドキュメントを検索すると、mutex メカニズムを提供する関数があることがわかりました。これらの機能は次のとおりです。
- sqlite3_mutex *sqlite3_db_mutex(sqlite3*); => データベース接続のポインターミューテックスを返します
- void sqlite3_mutex_enter(sqlite3_mutex*); =>クリティカルゾーンに入る
- void sqlite3_mutex_leave(sqlite3_mutex*); =>クリティカルゾーンを離れる
関数で試してみましたが、結果は同じです。異なるプロセスで情報を保存しようとすると(同じデータベースに書き込む)、情報が正しく保存されません。情報を格納する 2 つの関数に実装するコードは、より単純で次のとおりです。
最初の関数 => データを 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;
}
2 番目の関数は同じですが、同じデータベース ファイル内の別のテーブルに情報を格納します。
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 ミューテックス関数が適切に使用されており、適切に実行する必要があります。それとも、コードでのこれらの実装が間違っていますか?
· 複数のプロセスと並行して書き込み/読み取りデータベースを実装する別の種類のメカニズムはありますか? これらのメカニズムはどれで、どのように実装しますか?
私は数日前からこの問題を抱えていましたが、解決策が見つかりません。
どうもありがとう!