-
Notifications
You must be signed in to change notification settings - Fork 2
/
thread_store.h
131 lines (119 loc) · 2.8 KB
/
thread_store.h
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
* (C) 2007-2010 Taobao Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*
*
* Authors:
* yanran <[email protected]>
* - some work details if you want
*
*/
#ifndef _THREAD_STORE_H__
#define _THREAD_STORE_H__
#include <pthread.h>
# define UINT32_MAX (4294967295U)
class DfltThreadStoreAlloc
{
public:
void *malloc(const int64_t sz) { return ::malloc(sz); }
void free(void *p) { ::free(p); }
};
template <class Type>
class DfltInitType
{
public:
void operator()(void *ptr)
{
new (ptr) Type();
}
};
template <class Type, class InitType = DfltInitType<Type>,
class Alloc = DfltThreadStoreAlloc>
class thread_store
{
public:
static const pthread_key_t INVALID_THREAD_KEY = UINT32_MAX;
public:
thread_store() : key_(INVALID_THREAD_KEY)
{
create_store();
}
virtual ~thread_store()
{
delete_store();
}
static void destroy_object(void *mem)
{
if (NULL != mem)
{
thread_store<Type, InitType, Alloc> **h =
reinterpret_cast<thread_store<Type, InitType, Alloc> **>(mem) - 1;
(reinterpret_cast<Type *>(mem))->~Type();
(*h)->alloc_.free(h);
}
}
void create_store()
{
if (INVALID_THREAD_KEY == key_)
{
pthread_key_create(&key_, destroy_object);
}
}
void delete_store()
{
if (INVALID_THREAD_KEY != key_)
{
void* mem = pthread_getspecific(key_);
if (NULL != mem) destroy_object(mem);
pthread_key_delete(key_);
key_ = INVALID_THREAD_KEY;
}
}
Type* get()
{
if (INVALID_THREAD_KEY == key_) return NULL;
else
{
void* ptr = NULL;
void* mem = pthread_getspecific(key_);
if (NULL == mem)
{
mem = alloc_.malloc(sizeof(thread_store*) + sizeof(Type));
if (NULL != mem)
{
ptr = reinterpret_cast<void*>(
(reinterpret_cast<
thread_store<Type, InitType, Alloc> **
>(mem)) + 1
);
if (0 != pthread_setspecific(key_, ptr))
{
alloc_.free(mem);
mem = NULL;
ptr = NULL;
}
else
{
InitType init_type_func;
init_type_func(ptr);
*reinterpret_cast<thread_store<Type, InitType, Alloc> **>(mem)
= this;
}
}
}
else
{
ptr = mem;
}
return reinterpret_cast<Type*>(ptr);
}
}
private:
pthread_key_t key_;
Alloc alloc_;
};
#endif // _THREAD_STORE_H__