使用互斥锁和condition_variable时的异常
Exceptions while using mutex and condition_variable
我正在编写一个程序来从.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
相关文章:
- 处理多个异常集合的C++方法
- 我在c++代码中生成了一个运行时#3异常
- 孤立代码块在结构中引发异常
- C++中的赋值发生,尽管右侧出现异常
- C++ Singleton - Prevent ::instance() to variable
- 从构造函数抛出异常时如何克服内存泄漏
- 异常属于C++中的线程还是进程
- 当类定义不可见时捕获异常
- 引发异常:读取访问冲突**dynamicArray**为0x1118235.发生
- 为什么异常不退出程序?
- 为什么我应该在异常处理中使用std::cerr而不是std::cout
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 关于:C++中异常对象的范围:为什么我没有得到副本?
- 是什么导致了Unity 3D中的"错误线程异常"?
- 如何将strftime中的格式错误作为异常捕获
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 尝试使用智能指针时引发异常
- 函数如何通知用户它基于函数原型抛出异常?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 当我使用 C++ 中的 C# dll 来使用 Selenium 时,存在异常处理问题