我对 pthread_mutex_t 有疑问。当我尝试创建静态字段 pthread_mutex_t,然后在静态函数中对其进行初始化并最终在某些类方法中使用它时,我遇到了许多错误,例如:
main.o: In function `LogWriter::initialize(pthread_mutex_t*)':
main.cpp:(.text._ZN9LogWriter10initializeEP15pthread_mutex_t[LogWriter::initialize(pthread_mutex_t*)]+0x7): undefined reference to `LogWriter::mutex'
简化类代码:
class LogWriter{
static pthread_mutex_t mutex;
static void initialize(pthread_mutex_t *mut){
LogWriter::mutex = PTHREAD_MUTEX_INITIALIZER;
//if(pthread_mutex_init(&(LogWriter::mutex), NULL) != 0){
//init failed
//}
}
public:
static LogWriter getInstance(string module_name){
LogWriter instance(module_name);
return instance;
}
LogWriter& operator<<(string a);
};
我的问题是:为什么?我知道如果我将它定义为普通(非静态)字段,我不会有任何问题。也搜索了谷歌,但我找不到与此相关的任何材料。还创建指向静态 pthread_mutex 的指针并在主函数中初始化,就像这样结束。