使用c++11标准线程库时会出现段错误



我的程序崩溃了,我得到了以下消息。

segfault at 10 ip 00007f5a87e1ccd1 sp 00007f5a837d0bd8 error 4 in libpthread-2.17.so[7f5a87e13000+17000]

然后我检查了它发生的位置,它表明问题可能发生在pthread_mutex_destroy中。

[root@stock-1 tmp]# addr2line -e /lib64/libpthread.so.0 -f 0x9CD1
__GI___pthread_mutex_destroy
:?

由于这是我第一次遇到这个问题,而且我没能在我的开发环境中重现它,所以这些都是我能得到的信息。

在这个程序中,有一个主线程和多个工作线程。主线程创建工作线程并等待工作线程向其发送消息。工作线程完成任务并向主线程发送消息。

代码如下。

#ifndef MESSAGEQUEUE_H_
#define MESSAGEQUEUE_H_
#include <mutex>
#include <future>
#include <queue>
struct CopyResult
{
std::string mediaFile;
std::string type;
std::string status;
long long size;
int totalFileNumber = 0;
int errorType = 0;
std::string errorMessage;
};
template <class T>
class MessageQueue
{
public:
T receive()
{
std::unique_lock<std::mutex> uLock(_mutex);
_condtion.wait(uLock,[this]{return !_messages.empty();});
T msg = std::move(_messages.front());
_messages.pop_front();
return msg;
}
void send(T &&msg)
{
std::lock_guard<std::mutex> uLock(_mutex);
_messages.push_back(std::move(msg));
_condtion.notify_one();
}
private:
std::mutex _mutex;
std::condition_variable _condtion;
std::deque<T> _messages;
};
#endif

主线程

CopyResult result = queue_->receive();

工作线程

queue->send(std::move(result));

我搞不清出了什么问题。有人能帮忙吗?

好吧,如果没有最小可复制示例,我的猜测是:

您忘记调用(假设工作线程被称为worker_thread(:

if (worker_thread.joinable())
{
worker_thread.join();
}

当互斥锁已经在worker_thread的外部被破坏,但您试图将这个已经被破坏的互斥锁锁定在worker_hread内部时,会导致错误。对segfault的猜测是互斥体破坏。

p.S.另外,我建议您在GDB或类似调试器下的调试构建中运行程序,这真的很有用。它能够向您显示堆栈跟踪,这可能有助于检测您出现故障的位置和原因

最新更新