ThreadLocalStorage.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #ifndef HV_THREAD_LOCAL_STORAGE_H_
  2. #define HV_THREAD_LOCAL_STORAGE_H_
  3. #include "hexport.h"
  4. #include "hplatform.h"
  5. #ifdef OS_WIN
  6. #define hthread_key_t DWORD
  7. #define INVALID_HTHREAD_KEY 0xFFFFFFFF
  8. #define hthread_key_create(pkey) *pkey = TlsAlloc()
  9. #define hthread_key_delete TlsFree
  10. #define hthread_get_value TlsGetValue
  11. #define hthread_set_value TlsSetValue
  12. #else
  13. #define hthread_key_t pthread_key_t
  14. #define INVALID_HTHREAD_KEY 0xFFFFFFFF
  15. #define hthread_key_create(pkey) pthread_key_create(pkey, NULL)
  16. #define hthread_key_delete pthread_key_delete
  17. #define hthread_get_value pthread_getspecific
  18. #define hthread_set_value pthread_setspecific
  19. #endif
  20. #ifdef __cplusplus
  21. namespace hv {
  22. class HV_EXPORT ThreadLocalStorage {
  23. public:
  24. enum {
  25. THREAD_NAME = 0,
  26. EVENT_LOOP = 1,
  27. MAX_NUM = 16,
  28. };
  29. ThreadLocalStorage() {
  30. hthread_key_create(&key);
  31. }
  32. ~ThreadLocalStorage() {
  33. hthread_key_delete(key);
  34. }
  35. void set(void* val) {
  36. hthread_set_value(key, val);
  37. }
  38. void* get() {
  39. return hthread_get_value(key);
  40. }
  41. static void set(int idx, void* val);
  42. static void* get(int idx);
  43. static void setThreadName(const char* name);
  44. static const char* threadName();
  45. private:
  46. hthread_key_t key;
  47. static ThreadLocalStorage tls[MAX_NUM];
  48. };
  49. }
  50. #endif
  51. #endif // HV_THREAD_LOCAL_STORAGE_H_