C++ 在类中使用静态互斥锁

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2462961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:33:39  来源:igfitidea点击:

Using static mutex in a class

c++linuxmultithreadingboost

提问by Dmitry Yudakov

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.

我有一个类,我可以有很多实例。在它内部创建和初始化来自 3rd 方库(使用一些全局变量)的一些成员并且不是线程安全的。

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.

我想过使用静态 boost::mutex,它会被锁定在我的类构造函数和析构函数中。因此,在我的线程中创建和销毁实例对 3rd 方成员来说是安全的。



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?

  1. 我需要对这种静态成员进行一些特殊的初始化吗?

  2. 使用静态互斥量有什么问题吗?


Edit:Linking problem is fixed with correct definition in cpp


编辑:链接问题已通过 cpp 中的正确定义解决

boost::mutex MyClass::mx;

回答by Stephen C. Steel

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.

到带有 MyClass 实现的 cpp 文件。