FreeBASIC  0.91.0
thread_ctx.c
Go to the documentation of this file.
1 /* thread local context storage */
2 
3 #include "fb.h"
4 #include "fb_private_thread.h"
5 
6 #if defined ENABLE_MT && defined HOST_UNIX
7  #define FB_TLSENTRY pthread_key_t
8  #define FB_TLSALLOC(key) pthread_key_create( &(key), NULL )
9  #define FB_TLSFREE(key) pthread_key_delete( (key) )
10  #define FB_TLSSET(key,value) pthread_setspecific( (key), (const void *)(value) )
11  #define FB_TLSGET(key) pthread_getspecific( (key) )
12 #elif defined ENABLE_MT && defined HOST_WIN32
13  #define FB_TLSENTRY DWORD
14  #define FB_TLSALLOC(key) key = TlsAlloc( )
15  #define FB_TLSFREE(key) TlsFree( (key) )
16  #define FB_TLSSET(key,value) TlsSetValue( (key), (LPVOID)(value) )
17  #define FB_TLSGET(key) TlsGetValue( (key) )
18 #else
19  #define FB_TLSENTRY uintptr_t
20  #define FB_TLSALLOC(key) key = NULL
21  #define FB_TLSFREE(key) key = NULL
22  #define FB_TLSSET(key,value) key = (FB_TLSENTRY)value
23  #define FB_TLSGET(key) key
24 #endif
25 
27 
28 FBCALL void *fb_TlsGetCtx( int index, size_t len )
29 {
30  void *ctx = (void *)FB_TLSGET( __fb_tls_ctxtb[index] );
31 
32  if( ctx == NULL ) {
33  ctx = (void *)calloc( 1, len );
34  FB_TLSSET( __fb_tls_ctxtb[index], ctx );
35  }
36 
37  return ctx;
38 }
39 
40 FBCALL void fb_TlsDelCtx( int index )
41 {
42  void *ctx = (void *)FB_TLSGET( __fb_tls_ctxtb[index] );
43 
44  /* free mem block if any */
45  if( ctx != NULL ) {
46  free( ctx );
47  FB_TLSSET( __fb_tls_ctxtb[index], NULL );
48  }
49 }
50 
51 FBCALL void fb_TlsFreeCtxTb( void )
52 {
53  /* free all thread local storage ctx's */
54  int i;
55  for( i = 0; i < FB_TLSKEYS; i++ ) {
56  fb_TlsDelCtx( i );
57  }
58 }
59 
60 #ifdef ENABLE_MT
61 void fb_TlsInit( void )
62 {
63  /* allocate thread local storage keys */
64  int i;
65  for( i = 0; i < FB_TLSKEYS; i++ )
67 }
68 
69 void fb_TlsExit( void )
70 {
71  /* free thread local storage plus the keys */
72  int i;
73  for( i = 0; i < FB_TLSKEYS; i++ ) {
74  fb_TlsDelCtx( i );
75 
76  /* del key/index */
78  }
79 }
80 #endif