1、简单的单例模式实现
2、C++的构造函数不是线程安全的,所以上述代码在多线程的情况下是不安全的,原因是new Singelton时,这句话不是原子的,比如一个线程执行了new的同时,另一个线程对if进行判断(此时实例还没被创建出来)。在windows下模拟:
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#include <iostream>
#include <process.h>
#include <windows.h>
using
namespace
std;
class
Singelton{
private
:
Singelton(){
m_count ++;
printf
(
"Singelton begin\n"
);
Sleep(1000);
// 加sleep为了放大效果
printf
(
"Singelton end\n"
);
}
static
Singelton *single;
public
:
static
Singelton *GetSingelton();
static
void
print();
static
int
m_count;
};
Singelton *Singelton::single =
nullptr
;
int
Singelton::m_count = 0;
Singelton *Singelton::GetSingelton(){
if
(single ==
nullptr
){
single =
new
Singelton;
}
return
single;
}
void
Singelton::print(){
cout<<m_count<<endl;
}
// 回调函数
void
threadFunc(
void
*p){
DWORD
id = GetCurrentThreadId();
// 获得线程id
cout<<id<<endl;
Singelton::GetSingelton()->print();
// 构造函数并获得实例,调用静态成员函数
}
int
main(
int
argc,
const
char
* argv[]) {
int
threadNum = 3;
HANDLE
threadHdl[100];
// 创建3个线程
for
(
int
i = 0; i<threadNum; i++){
threadHdl[i] = (
HANDLE
)_beginthread(threadFunc, 0,
nullptr
);
}
// 让主进程等待所有的线程结束后再退出
for
(
int
i = 0; i<threadNum; i++){
WaitForSingleObject(threadHdl[i], INFINITE);
}
cout< |
首页 上一页 1 2 3 下一页 尾页 1/3/3 | |
【大 中 小】【打印】 【繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部】 | |
上一篇:Reliable Multicast Programming.. | 下一篇:选择排序的理解 |