thread.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Threads support
  2. //
  3. // Platform: ISO C++ 98/11 - POSIX
  4. // $Id$
  5. //
  6. // (c) __vic 2011
  7. #ifndef __VIC_THREAD_H
  8. #define __VIC_THREAD_H
  9. #include<__vic/defs.h>
  10. #include<pthread.h>
  11. namespace __vic {
  12. extern "C" void *__vic_thread_impl_func(void * );
  13. //////////////////////////////////////////////////////////////////////////////
  14. // Base class for thread objects
  15. class thread : private non_copyable
  16. {
  17. public:
  18. typedef ::pthread_t native_handle_type;
  19. thread() {}
  20. virtual ~thread();
  21. #if __cpp_rvalue_references
  22. thread(thread &&o) noexcept : tid(o.tid) { o.tid = id(); }
  23. thread &operator=(thread && ) noexcept;
  24. #endif
  25. class id
  26. {
  27. ::pthread_t tid;
  28. bool has_value_;
  29. typedef native_handle_type id::*unspecified_bool_type;
  30. public:
  31. id() : has_value_(false) {}
  32. explicit id(::pthread_t t) : tid(t), has_value_(true) {}
  33. operator unspecified_bool_type() const
  34. { return has_value_ ? &id::tid : 0; }
  35. native_handle_type handle() const { return tid; }
  36. friend bool operator==(id a, id b)
  37. {
  38. if(!a) return !b;
  39. return b && ::pthread_equal(a.tid, b.tid);
  40. }
  41. friend bool operator!=(id a, id b) { return !(a == b); }
  42. };
  43. void start();
  44. void cancel();
  45. void join();
  46. bool alive() const;
  47. bool joinable() const { return tid; }
  48. void kill(int );
  49. id get_id() const { return tid; }
  50. native_handle_type handle() const { return tid.handle(); }
  51. protected:
  52. virtual void worker() = 0;
  53. private:
  54. id tid;
  55. friend void *__vic_thread_impl_func(void * );
  56. };
  57. //////////////////////////////////////////////////////////////////////////////
  58. namespace this_thread
  59. {
  60. void sleep_ms(unsigned msec);
  61. inline thread::id get_id() { return thread::id(::pthread_self()); }
  62. }
  63. //////////////////////////////////////////////////////////////////////////////
  64. } // namespace
  65. #endif // header guard