Original Post
I was wanted to create a threaded logger for a real-time app. When the user calls logger.Log(message), the function will copy the message to a queue of messages and another thread will actually write them to disk so the real-time thread won't be hit by the slow performance of writing to the disk. My question what is the most effecient way is to store the message in the queue. I don't think option #1 is best b/c of constantly allocating and deallocating memory. Option #2 is probably better, but you have the drawback of potentially storing wasted space in the queue. (I am showing "pseduo" code that has not been compiled.) Option #1 Option #2
struct LogMessage
{
Time time;
char *message;
};
void Logger::Log(char *message)
{
if (!message)
return;
LogMessage log;
GetCurrentTime(log.time);
log.message = new char[strlen(message)+1];
strcpy(log.message, message);
AddToQueue(log);
}
struct LogMessage
{
Time time;
bool isPartial;
char message[256];
};
void Logger::Log(char *message)
{
if (!message)
return;
LogMessage log;
int len = strlen(message);
int MAX_LEN = sizeof(log.message)-1;
GetCurrentTime(log.time);
// check if we have to add multiple messages
if (len <= MAX_LEN)
{
log.isPartial = false;
strcpy(log.message, message);
AddToQueue(log);
}
else
{
log.isPartial = true;
do {
strncpy(log.message, message, MAX_LEN);
log.message[MAX_LEN] = '\0';
AddToQueue(log);
message += MAX_LEN;
len -= MAX_LEN;
} while (len > 0);
}
}