使用饿汉式,在类外创建静态对象,main函数执行前已经创建完成。线程安全。(thread.cpp)
编译:g++ -pthread thread.cpp
#include <pthread.h>
#include <unistd.h>
#include<iostream>
using namespace std;
class A
{
public:
static A* getInstance()
{
return &st_pa;
}
private:
A(){
cout << "A constructor 1 " << endl;
cout << "A constructor 2 " << endl;
}
static A st_pa;
};
A A::st_pa; //static成员类外定义初始化
void* mythread(void * vp)
{
cout << "mythread start " << endl;
A::getInstance();
cout << "mythread end" << endl;
return NULL;
}
void mainthread(void)
{
cout << "mainthread start " << endl;
A::getInstance();
cout << "mainthread end" << endl;
return ;
}
int main()
{
cout << "main function start!" <<endl;
pthread_t id1;
int ret = pthread_create(&id1, NULL, mythread, NULL);
mainthread();
cout << "pthread_join" << endl;
pthread_join(id1, NULL);
pthread_exit(0);
return 0;
}
输出结果:
不使用静态指针原因,程序结束后静态成员变量自动释放。