I have a log class, that class contains a stream defined as:ofstream logfile and a mutex to make sure that each time only one thread writes to the file (the program is multi-threaded).
The class is defined as:
#define LOG_NAME "log.txt"
using namespace std;
class Log
{
private:
pthread_mutex_t mutex_write;
ofstream logfile;
public:
Log();
~Log();
void Write (string txt);
};
The constructor is:
Log::Log()
{
pthread_mutex_init (&mutex_write,NULL);
pthread_mutex_lock (&mutex_write);
logfile.open(LOG_NAME, ios::out | ios::trunc);
logfile << "Created log file named " << LOG_NAME << endl;
pthread_mutex_unlock (&mutex_write);
}
The destructor is:
Log::~Log()
{
logfile << "Closing log file" << endl;
pthread_mutex_lock (&mutex_write);
logfile.close();
pthread_mutex_unlock (&mutex_write);
pthread_mutex_destroy (&mutex_write);
}
and:
void Log::Write (string txt)
{
pthread_mutex_lock (&mutex_write);
logfile << txt << endl;
pthread_mutex_unlock (&mutex_write);
}
In some of the times when the destructor is called, it can’t execute the line logfile.close(); because it says that it gets a segmentation fault, or it displays the message:
*** glibc detected *** corrupted double-linked list: 0x0000000000513eb0 ***
Abort
This doesn’t happen all the time, it seems to be happening randomly, at about 10% of the time. The program is multi-threaded (under linux).
Edit:
example of usage: (where log is a pointer to an object of Log class)
stringstream str;
str.str("");
str << "Ant " << i << " was created at place: (" << x << "," << y << ")";
log->Write (str.str());
or, if the string contains only knows text
log->Write ("Created board entity");
The problem was that we have a problem with checking that all threads have finished. We have repaired this, and now it works fine.
The problem probably happened because other threads tried to access a closed file, and sometimes tried to access a killed entity.