线程不与主线程连接

时间:2013-12-01 23:41:08

标签: multithreading c++11

我的记录器类有问题。 这是代码:

#include "Logger.h"

Logger::Logger()
{
    fileName = new string("log.txt");
    out = new ofstream(*fileName, ofstream::out);
    stream = new vector<string>;
    changed = new bool;
    condition = new condition_variable;
    myMutex = new mutex;
    running = new bool;

    if (running)
    {
        PostQuitMessage(500);
    }

    if (!out->is_open())
    {
        exit(3);
    }
    *running = false;

    T = new thread(&Logger::myrun, this);
}

Logger::~Logger()
{
    delete fileName;
delete out;
delete stream;
delete changed;
delete condition;
delete myMutex;
delete running;
delete T;
}

void Logger::myrun()
{
    *running = true;

    while (*running)
    {
        unique_lock<mutex> lock(*myMutex);
        condition->wait(lock, [this] { return *changed; });

        for (int c = 0; c < stream->size(); c++)
        {
            *out << stream->at(c) << endl;
        }

        stream->clear();

        *changed = false;
    }
    Sleep(100);
}

void Logger::log(string msg)
{
    unique_lock<mutex> lock(*myMutex);

    stream->push_back(msg);

    *changed = true;
    condition->notify_one();
}

void Logger::stop()
{
    *running = false;
    *changed = true;
    condition->notify_one();
    T->join();
    out->close();
}

线程在T-&gt; join();

行之后挂起

我的问题是 - 为什么会挂起来?我该如何解决呢?请告诉我代码:)

提前致谢!

P.S。所有的变量都是指针,因为我在dllexport中使用这个代码,VS给了我很多警告,它需要让dll-interface被类&#39; Logger&#39;&#的客户使用34 ;.如果有人对此有一些提示 - 欢迎您发帖:D

1 个答案:

答案 0 :(得分:0)

我通过将析构函数代码放入方法停止并在加入线程后关闭文件来解决问题。我想