单例模式中使用pthread_once 异常,求助

准备找工作的Ocean 2016-10-27 05:35:30
代码如下,编译出现 undefined reference to “pthread_once” ,明明包含了pthread.h了啊, 不明白,求指点
/*
#ifndef SINGLETON_H_
#define SINGLETON_H_
#include <pthread.h>
class Singleton {
public:
static Singleton * getInstance() {
if (instance == NULL) {
pthread_once(&once, once_init);
//pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
if (instance == NULL)
instance = new Singleton();
pthread_mutex_unlock(&mutex);
}
return instance;
}

private:
Singleton() {
}
~Singleton();
Singleton(const Singleton &s);

static void once_init(void) {
pthread_mutex_init(&mutex, NULL);
}
static Singleton *instance;
static pthread_mutex_t mutex;
static pthread_once_t once;

};
pthread_once_t Singleton::once = PTHREAD_ONCE_INIT;
pthread_mutex_t Singleton::mutex;
Singleton *Singleton::instance = NULL;
#endif /* SINGLETON_H_ */
...全文
665 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Frey_Liu 2017-09-19
  • 打赏
  • 举报
回复
提示编译时候找不到thread相关的函数定义,可以用“g++ -o main main.cpp -pthread”这样的方式编译就可以了。一楼回答是正确的。
nswcfd 2016-10-31
  • 打赏
  • 举报
回复
变量的定义或者Inline函数或者宏定义在头文件里,非inline函数的实现不在头文件里。 void xxx() { pthread_once(NULL, NULL); //undefined reference to `pthread_once' pthread_mutex_init(NULL, NULL); //OK pthread_mutex_lock(NULL); //OK pthread_create(NULL, NULL, NULL, NULL); //undefined reference to `pthread_create' } 可以不加-lpthread编译一下,看看报告几个undefined reference to `...'
  • 打赏
  • 举报
回复
引用 1 楼 nswcfd 的回复:
-lpthread或者-pthread
不是这个问题啊,pthread_mutex_t 这个就可以用啊
  • 打赏
  • 举报
回复
不是这个问题啊,pthread_mutex_t 这个就可以用啊
nswcfd 2016-10-28
  • 打赏
  • 举报
回复
-lpthread或者-pthread

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧