C++ Mac OS X pthread Initialization

C++ Mac OS X pthread Initialization

本文关键字:pthread Initialization OS Mac C++      更新时间:2023-10-16

我在Mac OS X 10.12上遇到了一个错误,涉及Clang,它不想编译我的代码。我希望它通过编译器编译,但它坚持我"错误:成员初始化器'pthread_mutex_init'不命名非静态数据成员或基类"时,调用pthread_mutex_init。我已经尝试在pthread_mutex_t声明前添加和删除"静态",我已经包含了我的pthread头文件

编辑:是的,我在我的file.cpp文件中包含了file.h。编辑#2:我试过mutex_ = (mutex_pthread_t)PTHREAD_MUTEX_INITIALIZER,它给了我一些奇怪的错误,告诉我在某处插入"{"。 下面是我的代码:
Memory.h: 
#include <pthread.h>
class Memory {
    static pthread_mutex_t mutex_;
}
Memory.cpp:
#include <Memory.h>
#include <pthread.h>
Memory::Memory() : 
#ifdef __APPLE__
    pthread_mutex_init(&mutex_, NULL);
#endif

我假设你想在所有内存对象之间共享一个互斥锁?

这里有两种(许多)方法,副作用略有不同:

#include <pthread.h>
class Memory {
  // I am assuming that you wanted the mutex to be initialised
  // at program start?
  static bool init_mutex();
  static pthread_mutex_t mutex_;
  static bool initialised;
};
bool Memory::initialised = init_mutex();
bool Memory::init_mutex()
{
  pthread_mutex_init(&mutex_, 0);
  return true;
}

// or what about upon first use of a Memory?
class Memory2
{
  struct impl {
    impl() {
      pthread_mutex_init(&mutex_, 0);
    }
    pthread_mutex_t mutex_;
  };
  static impl& get_impl()
  {
    static impl impl_;
    return impl_;
  }
  Memory2()
  {
    get_impl();
  }
};