c++ - c++多线程应用程序上的内存损坏

标签 c++ multithreading memory logging

我正在开发一个多线程 C++ 应用程序,并开发了一个日志模块。日志记录模块是一个静态类,我使用 Logger::Log(string file, string message) 调用它,它用 pair<string*,string*> 填充静态队列。队列本身是一个 queue<<pair<string*,string*>*> .一切都保存为指针,因为我试图避免垃圾收集,并且相信指针变量需要特定的删除来释放内存。

现在,当其中一个线程想要记录某些内容时,它会调用 Log 方法,该方法又追加到队列的末尾。

另一个线程遍历队列,弹出项目并将它们写入指定的文件。

由于某种原因,一些写入文件的文本已损坏,因为我丢失了消息的开头或结尾部分。

例如,如果我调用 Log("file", "this is my message"),在 Log 方法中我会在前面加上一个时间戳,并创建一个新字符串,因为我认为原始字符串可能会被覆盖,但是它仍然发生。 问题是在某些情况下,写入文件的是时间戳,加上消息的结尾。

这是 Logger 类的完整代码:

#include "Logger.h"

queue<pair<string*, string*>*> Logger::messages;

boost::mutex Logger::loggerLock;

void Logger::CleanOldFiles(vector<string> files){
    for (vector<string>::iterator it = files.begin(); it != files.end(); ++it) {
        string filePath = boost::filesystem::current_path().string() + "\\" + *it;
        int result = remove(filePath.c_str());
    }
}

void Logger::Init() {
    Logger::messages = queue<pair<string*, string*>*>();
    boost::thread workerThread(Logger::Process);
    //workerThread.start_thread();
}

void Logger::RawLog(string file, string message) {
    loggerLock.lock();
    string *f = new string(file);
    string *m = new string(message + "\n");
    messages.push(new pair<string*, string*>(f, m));
    loggerLock.unlock();
}

void Logger::Log(string file, string message) {
    loggerLock.lock();
    string *f = new string(file);
    string *m = new string(Functions::CurrentTime() + " (" + boost::lexical_cast<string>(boost::this_thread::get_id()) + "): " + message.c_str() + "\n");
    messages.push(new pair<string*, string*>(f, m));
    loggerLock.unlock();
}


void Logger::Process() {
    while (true) {
        if (Logger::messages.size() == 0) {
            boost::this_thread::sleep(boost::posix_time::milliseconds(200));
            continue;
        }
        loggerLock.lock();
        pair<string*, string*> *entry = messages.front();
        messages.pop();
        loggerLock.unlock();
        ofstream file(boost::filesystem::current_path().string() + "\\" + *(entry->first), ofstream::binary | ofstream::app);
        file.write(entry->second->c_str(), entry->second->length());
        file.close();
        delete entry->first;
        delete entry->second;
        delete entry;
        //cout << entry->second;
    }
}

我希望我说得足够清楚...

我不明白为什么会这样,任何人都可以给我一些关于如何避免这种情况的提示吗?

提前致谢。

最佳答案

Logger::Log 必须 是 MT 安全的,否则您可能会得到两个或多个线程同时尝试记录某些内容。使其 MT 安全的最简单方法是 mutex

关于c++ - c++多线程应用程序上的内存损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043274/

相关文章:

c - 哪个 Unix 没有线程安全的 malloc?

c - 自动局部变量是否存储在C中的堆栈中?

iphone - 为什么我的 Objective-C 对象被释放?

c++ - seekg 不工作

c++ - 将 Platform::Array<byte> 转换为字符串

c++ - 启用 C++14 英特尔编译器

c - 在malloc C/C++之前,malloc无需类型转换即可工作

c++ - 使用 Boost 库从 C++ 中的 JSON 中检索内容

java - 线程间共享数据

c# - 如何修复捕获TimeoutException?