pthread_tls.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <pthread.h>
  2. #include "pthread_internal.h"
  3. _pthread_key_data_t _thread_keys[PTHREAD_KEY_MAX];
  4. void pthread_key_system_init()
  5. {
  6. rt_memset(&_thread_keys[0], 0, sizeof(_thread_keys));
  7. }
  8. void *pthread_getspecific(pthread_key_t key)
  9. {
  10. struct _pthread_data* ptd;
  11. ptd = _pthread_get_data(rt_thread_self());
  12. RT_ASSERT(ptd != NULL);
  13. if (ptd->tls == NULL) return NULL;
  14. if ((key < PTHREAD_KEY_MAX) && (_thread_keys[key].is_used))
  15. return ptd->tls[key];
  16. return NULL;
  17. }
  18. RTM_EXPORT(pthread_getspecific);
  19. int pthread_setspecific(pthread_key_t key, const void *value)
  20. {
  21. struct _pthread_data* ptd;
  22. ptd = _pthread_get_data(rt_thread_self());
  23. RT_ASSERT(ptd != NULL);
  24. /* check tls area */
  25. if (ptd->tls == NULL)
  26. {
  27. ptd->tls = (void**)rt_malloc(sizeof(void*) * PTHREAD_KEY_MAX);
  28. }
  29. if ((key < PTHREAD_KEY_MAX) && _thread_keys[key].is_used)
  30. {
  31. ptd->tls[key] = (void *)value;
  32. return 0;
  33. }
  34. return EINVAL;
  35. }
  36. RTM_EXPORT(pthread_setspecific);
  37. int pthread_key_create(pthread_key_t *key, void (*destructor)(void*))
  38. {
  39. rt_uint32_t index;
  40. rt_enter_critical();
  41. for (index = 0; index < PTHREAD_KEY_MAX; index ++)
  42. {
  43. if (_thread_keys[index].is_used == 0)
  44. {
  45. _thread_keys[index].is_used = 1;
  46. _thread_keys[index].destructor = destructor;
  47. *key = index;
  48. rt_exit_critical();
  49. return 0;
  50. }
  51. }
  52. rt_exit_critical();
  53. return EAGAIN;
  54. }
  55. RTM_EXPORT(pthread_key_create);
  56. int pthread_key_delete(pthread_key_t key)
  57. {
  58. if (key >= PTHREAD_KEY_MAX) return EINVAL;
  59. rt_enter_critical();
  60. _thread_keys[key].is_used = 0;
  61. _thread_keys[key].destructor = 0;
  62. rt_exit_critical();
  63. return 0;
  64. }
  65. RTM_EXPORT(pthread_key_delete);