以下のコードでは、私の関数はデータ エントリをディスクに書き込み、エントリが記録されているファイルにオフセットを返すことになっています。ただし、複数のスレッドでコードを実行すると、この値が正確でないことがあります。このコードにスレッド セーフの問題はありますか?
// global file descriptor to current data file, shared amongst many threads
FILE* current_fp;
pthread_mutex_t my_mutex;
...
int main()
{
...
pthread_mutex_lock(&my_mutex);
current_fp = fopen(data_file, "ab");
if (current_fp == NULL)
{
fprintf(stderr, "%s: Unable to open file %s: %s\n", __func__, data_file, strerror_r(errno, ebuf, sizeof(ebuf)));
pthread_mutex_unlock(&ldb_mutex);
return -1;
}
pthread_mutex_unlock(&my_mutex);
return 0;
}
// write a data entry, and return the offset at which it will be stored
// I'm having an issue where it seems like *occasionally* the offset returned is not
// really the offset at which the entry was stored, with multiple threads
long write_log_entry(data_entry_t* entry)
{
int num_written;
long offset; // offset at which entry will be written
pthread_mutex_lock(&my_mutex);
// get the next offset in the file, which is where I expect
// the entry to be stored
offset = ftell(current_fp);
if (offset == -1)
{
error();
}
// an example -- the real code writes a bunch of data members of entry
int num_written = fwrite(entry, sizeof(data_entry_t), 1, current_fp);
if (num_written != 1)
{
error();
}
fflush(current_fp);
pthread_mutex_unlock(&my_mutex);
return offset;
}