使用互斥锁和condition_variable时的异常

Exceptions while using mutex and condition_variable

本文关键字:variable 异常 condition      更新时间:2023-10-16

我正在编写一个程序来从.txt文件中读取数据并将其用于输出.txt文件。我正在使用两个线程;第一个线程用于从.txt文件中读取数据,第二个线程用于将其写入输出文件。我是互斥体和condition_variable编程的初学者,不知何故我的程序处理异常......例外情况是

abort() has been called.

以下是两种线程方法:

void MessagesSender::readsData()
{
    ifstream data;
    data.open("data.txt");
    string buffer;
    bool toEmpty = false;
    std::unique_lock<mutex> locker(mtx, std::defer_lock);
    if (data.is_open())
    {
        while (std::getline(data, buffer)) //reads line to the buffer.
        {
            locker.lock();
            this->messages.push(buffer); //push the message to the queue.
            locker.unlock();
            cond.notify_one();
        }
        data.close();
        toEmpty = true;
    }
    else
    {
        cout << "Error opening file... " << endl;
    }
    if (toEmpty) //empty the data file.
    {
        ofstream emptyFile; 
        emptyFile.open("data.txt", ofstream::out | ofstream::trunc);
        emptyFile.close();
    }
}
void MessagesSender::sendsData()
{
    ofstream output;
    output.open("output.txt");
    string tempString;
    string tempMessage;
    if (output.is_open())
    {
        std::unique_lock<mutex> locker(mtx, std::defer_lock);
        locker.lock();
        cond.wait(locker);
        while (!(this->messages.empty()))
        {
            tempMessage = this->messages.front();
            this->messages.pop();
            locker.unlock();
            for (std::vector<string>::iterator it = this->userNames.begin(); it != this->userNames.end(); ++it)
            {
                tempString = *it;
                tempString += ": ";
                tempString += tempMessage;
                tempString += "n";
                output << tempString;
            }
        }
        output.close();
    }
    else
    {
        cout << "Error opening file... " << endl;
    }
}

为什么程序处理异常?

一个可能的错误是,即使互斥锁未锁定,您也会反复解锁 while 循环中的mutex

if (output.is_open())
    {
        std::unique_lock<mutex> locker(mtx, std::defer_lock);
        locker.lock();
        cond.wait(locker);
        while (!(this->messages.empty()))
        {
            tempMessage = this->messages.front();
            this->messages.pop();
            // if multiple messages are in the queue, you unlock multiple times 
            // even though the mutex is not locked
            locker.unlock();   
            for (std::vector<string>::iterator it = this->userNames.begin(); it != this->userNames.end(); ++it)
            {
                tempString = *it;
                tempString += ": ";
                tempString += tempMessage;
                tempString += "n";
                output << tempString;
            }
        }
        output.close();
    }

根据unique_lock::解锁,这会引发std::system_error