RAUL  0.5.1
Thread.hpp
1 /* This file is part of Raul.
2  * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
3  *
4  * Raul is free software; you can redistribute it and/or modify it under the
5  * terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * Raul is distributed in the hope that it will be useful, but WITHOUT ANY
10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
16  */
17 
18 #ifndef RAUL_THREAD_HPP
19 #define RAUL_THREAD_HPP
20 
21 #include <string>
22 #include <iostream>
23 #include <pthread.h>
24 #include <boost/utility.hpp>
25 
26 namespace Raul {
27 
28 
38 class Thread : boost::noncopyable
39 {
40 public:
41  virtual ~Thread() {
42  stop();
43  }
44 
45  static Thread* create(const std::string& name="")
46  { return new Thread(name); }
47 
49  static Thread* create_for_this_thread(const std::string& name="")
50  { return new Thread(pthread_self(), name); }
51 
52  static Thread& get();
53 
54  virtual void start();
55  virtual void stop();
56 
57  void set_scheduling(int policy, unsigned int priority);
58 
59  const std::string& name() const { return _name; }
60  void set_name(const std::string& name) { _name = name; }
61 
62  unsigned context() const { return _context; }
63  void set_context(unsigned context) { _context = context; }
64 
65 protected:
66  Thread(const std::string& name="");
67  Thread(pthread_t thread, const std::string& name="");
68 
77  virtual void _run() {}
78 
79  bool _exit_flag;
80 
81 private:
82 
83  inline static void* _static_run(void* me) {
84  pthread_setspecific(_thread_key, me);
85  Thread* myself = (Thread*)me;
86  myself->_run();
87  myself->_pthread_exists = false;
88  return NULL; // and I
89  }
90 
92  static void thread_key_alloc()
93  {
94  pthread_key_create(&_thread_key, NULL);
95  }
96 
97  /* Key for the thread-specific buffer */
98  static pthread_key_t _thread_key;
99 
100  /* Once-only initialisation of the key */
101  static pthread_once_t _thread_key_once;
102 
103  unsigned _context;
104  std::string _name;
105  bool _pthread_exists;
106  pthread_t _pthread;
107 };
108 
109 
110 } // namespace Raul
111 
112 #endif // RAUL_THREAD_HPP
Abstract base class for a thread.
Definition: Thread.hpp:38
static Thread * create_for_this_thread(const std::string &name="")
Must be called from thread.
Definition: Thread.hpp:49
virtual void _run()
Thread function to execute.
Definition: Thread.hpp:77