forked from Tencent/libco
-
Notifications
You must be signed in to change notification settings - Fork 1
/
co_routine_specific.h
86 lines (77 loc) · 2.19 KB
/
co_routine_specific.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
/*
* Tencent is pleased to support the open source community by making Libco available.
* Copyright (C) 2014 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <pthread.h>
#include <stdlib.h>
/*
invoke only once in the whole program
CoRoutineSetSpecificCallBack(CoRoutineGetSpecificFunc_t pfnGet,CoRoutineSetSpecificFunc_t pfnSet)
struct MyData_t
{
int iValue;
char szValue[100];
};
CO_ROUTINE_SPECIFIC( MyData_t,__routine );
int main()
{
CoRoutineSetSpecificCallBack( co_getspecific,co_setspecific );
__routine->iValue = 10;
strcpy( __routine->szValue,"hello world" );
return 0;
}
*/
extern int co_setspecific( pthread_key_t key, const void *value );
extern void * co_getspecific( pthread_key_t key );
#define CO_ROUTINE_SPECIFIC( name,y ) \
\
static pthread_once_t _routine_once_##name = PTHREAD_ONCE_INIT; \
static pthread_key_t _routine_key_##name;\
static int _routine_init_##name = 0;\
static void _routine_make_key_##name() \
{\
(void) pthread_key_create(&_routine_key_##name, NULL); \
}\
template <class T>\
class clsRoutineData_routine_##name\
{\
public:\
inline T *operator->()\
{\
if( !_routine_init_##name ) \
{\
pthread_once( &_routine_once_##name,_routine_make_key_##name );\
_routine_init_##name = 1;\
}\
T* p = (T*)co_getspecific( _routine_key_##name );\
if( !p )\
{\
p = (T*)calloc(1,sizeof( T ));\
int ret = co_setspecific( _routine_key_##name,p) ;\
if ( ret )\
{\
if ( p )\
{\
free(p);\
p = NULL;\
}\
}\
}\
return p;\
}\
};\
\
static clsRoutineData_routine_##name<name> y;