source: cpp/common/threads.h @ 111

Last change on this file since 111 was 109, checked in by sz, 11 years ago

source reorganization (see README)
new feature added: part/joint shapes (see frams/_demos/part_shapes.cpp)

  • Property svn:eol-style set to native
File size: 1.7 KB
Line 
1#ifndef _THREADS_H_
2#define _THREADS_H_
3
4#ifdef MULTITHREADED
5
6#include <pthread.h>
7
8int sysGetCPUCount();
9
10#ifdef LINUX
11//#define USE_CPP_TLS
12//#define CPP_TLS __thread
13#endif
14
15#ifdef __BORLANDC__ //zakladamy ze wszyscy uzywaja pthreadsowych, bo w tych wbudowanych w c++ w obecnym standardzie nie ma destrukcji obiektow (tylko proste struktury)
16//#define USE_CPP_TLS
17//#define CPP_TLS __declspec(thread)
18#endif
19
20template<class T> class ThreadSingleton
21{
22pthread_key_t mt_key;
23
24  public:
25
26ThreadSingleton()
27 {
28 pthread_key_create(&mt_key,&destructor);
29 }
30
31~ThreadSingleton()
32 {
33 T* o=set(NULL);
34 if (o) delete o;
35 }
36
37static void destructor(void* o)
38 {
39 if (o)
40         delete (T*)o;
41 }
42
43T* set(T* new_o)
44 {
45 T* o=(T*)pthread_getspecific(mt_key);
46 pthread_setspecific(mt_key,new_o);
47 return o;
48 }
49
50T* get()
51 {
52 T* o=(T*)pthread_getspecific(mt_key);
53 if (!o)
54         {
55         o=new T();
56         pthread_setspecific(mt_key,o);
57         }
58 return o;
59 }
60
61T& getref() {return *get();}
62};
63
64#else
65
66template<class T> class ThreadSingleton
67{
68T object;
69
70  public:
71
72T* get() {return &object;}
73T& getref() {return object;}
74};
75
76#endif
77
78////////////////////////////////////
79
80#ifdef USE_CPP_TLS
81
82// use c++ implementation (CPP_TLS must also be defined)
83
84#define THREAD_LOCAL_DECL(cls,var) CPP_TLS cls* var
85#define THREAD_LOCAL_DEF(cls,var) CPP_TLS cls* var=NULL
86
87template<class T> T* tlsGet(T*& var)
88{
89if (!var)
90        var=new T();
91return var;
92}
93
94#define tlsGetRef(var) (*tlsGet(var))
95
96template<class T> T* tlsSet(T*& var,T* new_o)
97{
98T* o=var;
99var=new_o;
100return o;
101}
102
103#else
104
105// use pthreads implementation
106
107#define THREAD_LOCAL_DECL(cls,var) ThreadSingleton<cls> var
108#define THREAD_LOCAL_DEF(cls,var) ThreadSingleton<cls> var
109#define tlsGet(var) var.get()
110#define tlsGetRef(var) var.getref()
111#define tlsSet(var,o) var.set(o)
112
113#endif
114
115
116#endif
Note: See TracBrowser for help on using the repository browser.