pthread_tls.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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) ptd->tls = rt_malloc(sizeof(void*) * PTHREAD_KEY_MAX);
  25. if ((key < PTHREAD_KEY_MAX) && _thread_keys[key].is_used)
  26. {
  27. ptd->tls[key] = (void *)value;
  28. return 0;
  29. }
  30. return EINVAL;
  31. }
  32. int pthread_key_create(pthread_key_t *key, void (*destructor)(void*))
  33. {
  34. rt_uint32_t index;
  35. rt_enter_critical();
  36. for (index = 0; index < PTHREAD_KEY_MAX; index ++)
  37. {
  38. if (_thread_keys[index].is_used == 0)
  39. {
  40. _thread_keys[index].is_used = 1;
  41. _thread_keys[index].destructor = destructor;
  42. *key = index;
  43. rt_exit_critical();
  44. return 0;
  45. }
  46. }
  47. rt_exit_critical();
  48. return EAGAIN;
  49. }
  50. int pthread_key_delete(pthread_key_t key)
  51. {
  52. if (key >= PTHREAD_KEY_MAX) return EINVAL;
  53. rt_enter_critical();
  54. _thread_keys[key].is_used = 0;
  55. _thread_keys[key].destructor = 0;
  56. rt_exit_critical();
  57. return 0;
  58. }