pthread_tls.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. int pthread_setspecific(pthread_key_t key, const void *value)
  19. {
  20. struct _pthread_data* ptd;
  21. ptd = _pthread_get_data(rt_thread_self());
  22. RT_ASSERT(ptd != NULL);
  23. /* check tls area */
  24. if (ptd->tls == NULL)
  25. {
  26. ptd->tls = (void**)rt_malloc(sizeof(void*) * PTHREAD_KEY_MAX);
  27. }
  28. if ((key < PTHREAD_KEY_MAX) && _thread_keys[key].is_used)
  29. {
  30. ptd->tls[key] = (void *)value;
  31. return 0;
  32. }
  33. return EINVAL;
  34. }
  35. int pthread_key_create(pthread_key_t *key, void (*destructor)(void*))
  36. {
  37. rt_uint32_t index;
  38. rt_enter_critical();
  39. for (index = 0; index < PTHREAD_KEY_MAX; index ++)
  40. {
  41. if (_thread_keys[index].is_used == 0)
  42. {
  43. _thread_keys[index].is_used = 1;
  44. _thread_keys[index].destructor = destructor;
  45. *key = index;
  46. rt_exit_critical();
  47. return 0;
  48. }
  49. }
  50. rt_exit_critical();
  51. return EAGAIN;
  52. }
  53. int pthread_key_delete(pthread_key_t key)
  54. {
  55. if (key >= PTHREAD_KEY_MAX) return EINVAL;
  56. rt_enter_critical();
  57. _thread_keys[key].is_used = 0;
  58. _thread_keys[key].destructor = 0;
  59. rt_exit_critical();
  60. return 0;
  61. }