PageRenderTime 27ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/mordor/thread.h

http://github.com/mozy/mordor
C Header | 96 lines | 63 code | 17 blank | 16 comment | 0 complexity | ba20641aebda37127fc48cc66a4155ab MD5 | raw file
Possible License(s): BSD-3-Clause
  1. #ifndef __MORDOR_THREAD_H__
  2. #define __MORDOR_THREAD_H__
  3. // Copyright (c) 2010 - Mozy, Inc.
  4. #include <iosfwd>
  5. #include <boost/function.hpp>
  6. #include <boost/noncopyable.hpp>
  7. #include "version.h"
  8. #ifndef WINDOWS
  9. #include "semaphore.h"
  10. #endif
  11. namespace Mordor {
  12. #ifdef WINDOWS
  13. typedef DWORD tid_t;
  14. #elif defined(LINUX)
  15. typedef pid_t tid_t;
  16. #elif defined(OSX)
  17. typedef mach_port_t tid_t;
  18. #else
  19. typedef pthread_t tid_t;
  20. #endif
  21. inline tid_t emptytid() { return (tid_t)-1; }
  22. tid_t gettid();
  23. class Scheduler;
  24. class Thread : boost::noncopyable
  25. {
  26. public:
  27. /// thread bookmark
  28. ///
  29. /// bookmark current thread id and scheduler, allow to switch back to
  30. /// the same thread id later.
  31. /// @pre The process must be running with available scheduler, otherwise
  32. /// it is not possible to switch execution between threads with bookmark.
  33. /// @note Bookmark was designed to address the issue where we failed to
  34. /// rethrow an exception in catch block, because GCC C++ runtime saves the
  35. /// exception stack in a pthread TLS variable. and swapcontext(3) does not
  36. /// take care of TLS. but developer needs to be more aware of underlying
  37. /// thread using thread bookmark, so we developed another way to fix this
  38. /// problem. thus bookmark only serve as a way which allow user to stick
  39. /// to a native thread.
  40. class Bookmark
  41. {
  42. public:
  43. Bookmark();
  44. /// switch to bookmark's tid
  45. void switchTo();
  46. /// bookmark's tid
  47. tid_t tid() const { return m_tid; }
  48. private:
  49. Scheduler *m_scheduler;
  50. tid_t m_tid;
  51. };
  52. public:
  53. Thread(boost::function<void ()> dg, const char *name = NULL);
  54. ~Thread();
  55. tid_t tid() const { return m_tid; }
  56. void join();
  57. private:
  58. static
  59. #ifdef WINDOWS
  60. unsigned WINAPI
  61. #else
  62. void *
  63. #endif
  64. run(void *arg);
  65. private:
  66. tid_t m_tid;
  67. #ifdef WINDOWS
  68. HANDLE m_hThread;
  69. #else
  70. pthread_t m_thread;
  71. #endif
  72. #ifdef LINUX
  73. boost::function<void ()> m_dg;
  74. Semaphore m_semaphore;
  75. const char *m_name;
  76. #endif
  77. };
  78. }
  79. #endif