tls.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // Name: wx/unix/tls.h
  3. // Purpose: Pthreads implementation of wxTlsValue<>
  4. // Author: Vadim Zeitlin
  5. // Created: 2008-08-08
  6. // Copyright: (c) 2008 Vadim Zeitlin <vadim@wxwidgets.org>
  7. // Licence: wxWindows licence
  8. ///////////////////////////////////////////////////////////////////////////////
  9. #ifndef _WX_UNIX_TLS_H_
  10. #define _WX_UNIX_TLS_H_
  11. #include <pthread.h>
  12. // ----------------------------------------------------------------------------
  13. // wxTlsKey is a helper class encapsulating the TLS value index
  14. // ----------------------------------------------------------------------------
  15. class wxTlsKey
  16. {
  17. public:
  18. // ctor allocates a new key and possibly registering a destructor function
  19. // for it
  20. wxTlsKey(wxTlsDestructorFunction destructor)
  21. {
  22. m_destructor = destructor;
  23. if ( pthread_key_create(&m_key, destructor) != 0 )
  24. m_key = 0;
  25. }
  26. // return true if the key was successfully allocated
  27. bool IsOk() const { return m_key != 0; }
  28. // get the key value, there is no error return
  29. void *Get() const
  30. {
  31. return pthread_getspecific(m_key);
  32. }
  33. // change the key value, return true if ok
  34. bool Set(void *value)
  35. {
  36. void *old = Get();
  37. if ( old )
  38. m_destructor(old);
  39. return pthread_setspecific(m_key, value) == 0;
  40. }
  41. // free the key
  42. ~wxTlsKey()
  43. {
  44. if ( IsOk() )
  45. pthread_key_delete(m_key);
  46. }
  47. private:
  48. wxTlsDestructorFunction m_destructor;
  49. pthread_key_t m_key;
  50. wxDECLARE_NO_COPY_CLASS(wxTlsKey);
  51. };
  52. #endif // _WX_UNIX_TLS_H_