C++ 增强互斥体和线程
我有几个单例类,其中包含一些额外的函数,这些函数在单独的线程中运行。结构如下所示:C++ 增强互斥体和线程,c++,multithreading,exception,boost,mutex,C++,Multithreading,Exception,Boost,Mutex,我有几个单例类,其中包含一些额外的函数,这些函数在单独的线程中运行。结构如下所示: class Singleton { private: boost::mutex mMutex; std::vector<std::string> mMessages; public: void AddMessage(const std::string &msg) { mMutex.lock();
class Singleton
{
private:
boost::mutex mMutex;
std::vector<std::string> mMessages;
public:
void AddMessage(const std::string &msg)
{
mMutex.lock();
mMessages.push_back(msg);
mMutex.unlock();
}
void Sender()
{
while (true) {
mMutex.lock();
for (size_t i = 0; i < mMessages.size(); ++i)
{
// Do something with mMessages[i]
}
mMutex.unlock();
}
}
};
...
int main()
{
Singleton *handle;
handle = Singleton::instance();
boost::thread sender(boost::bind(&Singleton::Sender, handle));
... app cycle ...
}
类单例
{
私人:
boost::互斥mMutex;
std::向量消息;
公众:
void AddMessage(const std::string和msg)
{
mMutex.lock();
M消息。推回(msg);
mMutex.unlock();
}
无效发送者()
{
while(true){
mMutex.lock();
对于(size_t i=0;i
有时它会出错:
在抛出的实例后调用terminate
'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::lock_error> >'
what(): boost::lock_error
Aborted
'boost::exception\u detail::clone\u impl'
what():boost::lock\u错误
流产
找出断言的原因可能是什么?最好的原因是什么?可能是您没有创建对象
单例!因此互斥也不会被创建
尝试:
作为补充说明,您应该使用像boost::scoped_lock这样的锁,而不仅仅是锁定mutexe如果mMessages为空,那么Sender()函数将在不执行任何操作的情况下旋转。您应该在这里使用一个条件变量,让线程阻塞,直到有事情要做。@TorstenRobitzki是的,线程处于休眠状态。我只是决定不在exampleDo中显示这一点,正如Nikko所说,否则,如果您的代码抛出异常,您将陷入大麻烦!哦,对不起。不,在创建句柄后,我初始化它。
int main()
{
Singleton handle; //object, not pointer
boost::thread sender(boost::bind(&Singleton::Sender, &handle));
...
}