00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018 #ifndef RAUL_THREAD_HPP
00019 #define RAUL_THREAD_HPP
00020
00021 #include <string>
00022 #include <iostream>
00023 #include <pthread.h>
00024 #include <boost/utility.hpp>
00025
00026 namespace Raul {
00027
00028
00038 class Thread : boost::noncopyable
00039 {
00040 public:
00041 virtual ~Thread() {
00042 stop();
00043 }
00044
00045 static Thread* create(const std::string& name="")
00046 { return new Thread(name); }
00047
00049 static Thread* create_for_this_thread(const std::string& name="")
00050 { return new Thread(pthread_self(), name); }
00051
00052 static Thread& get();
00053
00054 virtual void start();
00055 virtual void stop();
00056
00057 void set_scheduling(int policy, unsigned int priority);
00058
00059 const std::string& name() const { return _name; }
00060 void set_name(const std::string& name) { _name = name; }
00061
00062 unsigned context() const { return _context; }
00063 void set_context(unsigned context) { _context = context; }
00064
00065 protected:
00066 Thread(const std::string& name="");
00067 Thread(pthread_t thread, const std::string& name="");
00068
00077 virtual void _run() {}
00078
00079 bool _exit_flag;
00080
00081 private:
00082
00083 inline static void* _static_run(void* me) {
00084 pthread_setspecific(_thread_key, me);
00085 Thread* myself = (Thread*)me;
00086 myself->_run();
00087 myself->_pthread_exists = false;
00088 return NULL;
00089 }
00090
00092 static void thread_key_alloc()
00093 {
00094 pthread_key_create(&_thread_key, NULL);
00095 }
00096
00097
00098 static pthread_key_t _thread_key;
00099
00100
00101 static pthread_once_t _thread_key_once;
00102
00103 unsigned _context;
00104 std::string _name;
00105 bool _pthread_exists;
00106 pthread_t _pthread;
00107 };
00108
00109
00110 }
00111
00112 #endif // RAUL_THREAD_HPP