c++ - 如何在条件变量等待时关闭时阻止 C++ 程序崩溃?

标签 c++ multithreading mutex condition-variable

我正在为我的项目构建一个多线程服务器。
我正在使用条件变量和锁。
我将条件变量 cv 作为全局变量,并将互斥体 _mtxReceivedMessages 作为类成员。

这是等待用户消息的函数:

void Server::handleReceivedMessages()
{
 while (1)
 {
    std::unique_lock<std::mutex> lck(_mtxReceivedMessages);
    while (_queRcvMessages.size() == 0) cv.wait(lck); // As long as there are 0 messages in the queue
 }
}

这是调用通知 cv 的函数:

void Server::addReceivedMessage(ReceivedMessage* msg)
{
    _queRcvMessages.push(msg); // Adds the message to the queue
    cv.notify_all(); // Unlockes all locked functions
}

问题是,如果我在函数 handleReceivedMessages 等待时(在调用函数 addReceivedMessage 之前)尝试关闭程序,程序就会崩溃,
但如果我删除该行:

 while (_queRcvMessages.size() == 0) cv.wait(lck); // As long as there are 0 messages in the queue

程序正常退出。

程序崩溃:Nuvola.exe 中 0x7748507C (ntdll.dll) 处出现未处理的异常:0xC000000D:传递给服务或函数的参数无效。

可能是什么问题?

最佳答案

如果你想干净关闭,你需要把它设计到所有东西中。您的服务器需要一个关闭函数(可以是它的析构函数)。您的 handleReceivedMessages 函数需要一种在关机时停止的方法。

例如,您可以将 bool shutdown; 添加到您的 Server 类。要关闭类,获取互斥锁,将 shutdown 设置为 true,并向条件变量发出信号。 (您可能需要加入服务器的线程,如果它有的话。)

您的 handleReceivedMessages 函数看起来更像这样:

void Server::handleReceivedMessages()
{
 while (1)
 {
    std::unique_lock<std::mutex> lck(_mtxReceivedMessages);
    while (!shutdown && _queRcvMessages.size() == 0) cv.wait(lck); // As long as there are 0 messages in the queue
    if (shutdown) return;
 }
}

关于c++ - 如何在条件变量等待时关闭时阻止 C++ 程序崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47421064/

相关文章:

java - 停止线程时是否必须抛出 InterruptedException?我可以使用其他异常类型吗?

c - Socket编程客户端服务器消息读写C

c++ - QSqlite 的变化

c++ - 将 txt 中的值分配给变量以保留计数器 - C++

java - 线程写入本地txt文件的问题

go - 具有 CRUD 操作的 RW 锁

http - 在包级别声明互斥变量是一种好习惯吗?

c++ - 如何在 Visual Studio 2015 中构建具有循环依赖项的 C++ 项目?

c++ - 私有(private) friend 运营商的代理类<<

java - 在JMS/ActiveMQ中如何使用同步来保持MessageConsumer的存活?