-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path18-P9.cc
36 lines (35 loc) · 993 Bytes
/
18-P9.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// 单例模式----std::call_once(c11引入)
#include <iostream>
#include <thread>
#include <unistd.h>
#include <mutex> //mutex, once_flag
std::mutex m;
std::once_flag of;
class SingletonClass
{
public:
static SingletonClass *GetInstance()
{
static SingletonClass *instance=nullptr; //C++会保证static多线程安全吗?
// call_once可以确保函数(第二个参数)只执行一次, call_once()自带互斥能力, 它是线程安全的, 第一个参数(of(once_flag))有互斥锁的作用.
std::call_once(of, [&](){instance = new SingletonClass();});
return instance;
}
private:
SingletonClass(){};
};
void a_func()
{
SingletonClass *scp = SingletonClass::GetInstance();
std::cout << std::endl
<< scp << std::endl;
}
int main(int argc, char const *argv[])
{
std::thread trd1(a_func);
std::thread trd2(a_func);
trd1.join();
trd2.join();
std::cout << "this is a main!" << std::endl;
return 0;
}