source: cpp/common/threads.h @ 308

Last change on this file since 308 was 286, checked in by Maciej Komosinski, 10 years ago

Updated headers

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