在一个类中使用静态互斥 [英] Using static mutex in a class

查看:642
本文介绍了在一个类中使用静态互斥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我可以有很多实例。它里面创建和初始化从第三方库一些成员(即使用一些全局变量),而不是线程安全的。

我想过用静态的boost ::互斥体,将被锁在我的类构造函数和析构函数。因此,创建和销毁我的线程之间的实例将是第三方成员的安全。

 MyClass类{
  静态的boost ::互斥MX;  //第三方库成员
上市:
  我的课();
  〜MyClass的();
};MyClass的MyClass的::()
{
  提高::互斥:: scoped_lock中的scoped_lock(MX);
  //创建和init第三方库的东西
}MyClass的::〜MyClass的()
{
  提高::互斥:: scoped_lock中的scoped_lock(MX);
  //破坏第三方库的东西
}

我不能链接,因为我收到错误:

 未定义的参考`MyClass的:: mx`


  1. 我需要这样的静态成员的一些特殊的初始化?


  2. 有什么不对有关使用静态互斥?


结果
修改链接问题被解决与CPP正确定义

 的boost ::互斥MyClass的:: MX;


解决方案

您已经声明,但没有定义你的类的静态互斥。只需添加行

 的boost ::互斥MyClass的:: MX;

与MyClass的实施cpp文件。

I have a class that I can have many instances of. Inside it creates and initializes some members from a 3rd party library (that use some global variables) and is not thread-safe.

I thought about using static boost::mutex, that would be locked in my class constructor and destructor. Thus creating and destroying instances among my threads would be safe for the 3rd party members.



class MyClass

{
  static boost::mutex mx;

  // 3rd party library members
public:
  MyClass();
  ~MyClass();
};

MyClass::MyClass()
{
  boost::mutex::scoped_lock scoped_lock(mx);
  // create and init 3rd party library stuff
}

MyClass::~MyClass()
{
  boost::mutex::scoped_lock scoped_lock(mx);
  // destroy 3rd party library stuff
}


I cannot link because I receive error:

undefined reference to `MyClass::mx`

  1. Do I need some special initialization of such static member?

  2. Is there anything wrong about using static mutex?


Edit: Linking problem is fixed with correct definition in cpp

boost::mutex MyClass::mx;

解决方案

You have declared, but not defined your class static mutex. Just add the line

boost::mutex MyClass::mx;

to the cpp file with the implementation of MyClass.

这篇关于在一个类中使用静态互斥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆