MPD  0.20.15
Thread.hxx
Go to the documentation of this file.
1 /*
2  * Copyright 2003-2017 The Music Player Daemon Project
3  * http://www.musicpd.org
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 
20 #ifndef MPD_THREAD_HXX
21 #define MPD_THREAD_HXX
22 
23 #include "check.h"
24 #include "Compiler.h"
25 
26 #ifdef _WIN32
27 #include <windows.h>
28 #else
29 #include <pthread.h>
30 #endif
31 
32 #include <assert.h>
33 
34 class Thread {
35 #ifdef _WIN32
36  HANDLE handle = nullptr;
37  DWORD id;
38 #else
39  pthread_t handle;
40  bool defined = false;
41 
42 #ifndef NDEBUG
43 
48  bool creating = false;
49 #endif
50 #endif
51 
52  void (*f)(void *ctx);
53  void *ctx;
54 
55 public:
56  Thread() = default;
57 
58  Thread(const Thread &) = delete;
59 
60 #ifndef NDEBUG
61  ~Thread() {
62  /* all Thread objects must be destructed manually by calling
63  Join(), to clean up */
64  assert(!IsDefined());
65  }
66 #endif
67 
68  bool IsDefined() const {
69 #ifdef _WIN32
70  return handle != nullptr;
71 #else
72  return defined;
73 #endif
74  }
75 
79  gcc_pure
80  bool IsInside() const noexcept {
81 #ifdef _WIN32
82  return GetCurrentThreadId() == id;
83 #else
84 #ifdef NDEBUG
85  constexpr bool creating = false;
86 #endif
87  return IsDefined() && (creating ||
88  pthread_equal(pthread_self(), handle));
89 #endif
90  }
91 
92  bool Start(void (*f)(void *ctx), void *ctx);
93  void Join();
94 
95 private:
96 #ifdef _WIN32
97  static DWORD WINAPI ThreadProc(LPVOID ctx);
98 #else
99  static void *ThreadProc(void *ctx);
100 #endif
101 
102 };
103 
104 #endif
bool Start(void(*f)(void *ctx), void *ctx)
~Thread()
Definition: Thread.hxx:61
void Join()
Thread()=default
gcc_pure bool IsInside() const noexcept
Check if this thread is the current thread.
Definition: Thread.hxx:80
#define gcc_pure
Definition: Compiler.h:116
bool IsDefined() const
Definition: Thread.hxx:68