I have a log class, this class contains a stream defined as: ofstream logfileand a mutex so that each time only one stream is written to the file (the program is multithreaded). A 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);
};
Constructor:
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);
}
Destructor:
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);
}
At the time the destructor is called, it cannot execute the line logfile.close();because it says it is getting a segmentation error or it displays a message:
*** glibc detected *** corrupted double-linked list: 0x0000000000513eb0 ***
Abort
This does not always happen, it happens randomly in about 10% of cases. The program is multithreaded (under Linux).
Edit:
usage example: (where logis a pointer to a class object log)
stringstream str;
str.str("");
str << "Ant " << i << " was created at place: (" << x << "," << y << ")";
log->Write (str.str());
or if the string contains only text
log->Write ("Created board entity");