OpenTTD
thread.h
Go to the documentation of this file.
1 /* $Id$ */
2 
3 /*
4  * This file is part of OpenTTD.
5  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8  */
9 
12 #ifndef THREAD_H
13 #define THREAD_H
14 
15 #include "debug.h"
16 #include <system_error>
17 #include <thread>
18 
21 
22 
27 inline void CSleep(int milliseconds)
28 {
29  std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
30 }
31 
36 void SetCurrentThreadName(const char *name);
37 
38 
49 template<class TFn, class... TArgs>
50 inline bool StartNewThread(std::thread *thr, const char *name, TFn&& _Fx, TArgs&&... _Ax)
51 {
52 #ifndef NO_THREADS
53  try {
54  std::thread t([] (const char *name, TFn&& F, TArgs&&... A) {
56  try {
57  /* Call user function with the given arguments. */
58  F(A...);
59  } catch (OTTDThreadExitSignal&) {
60  } catch (...) {
61  NOT_REACHED();
62  }
63  }, name, std::forward<TFn>(_Fx), std::forward<TArgs>(_Ax)...);
64 
65  if (thr != nullptr) {
66  *thr = std::move(t);
67  } else {
68  t.detach();
69  }
70 
71  return true;
72  } catch (const std::system_error& e) {
73  /* Something went wrong, the system we are running on might not support threads. */
74  DEBUG(misc, 1, "Can't create thread '%s': %s", name, e.what());
75  }
76 #endif
77 
78  return false;
79 }
80 
81 #endif /* THREAD_H */
Functions related to debugging.
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:27
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:50
void SetCurrentThreadName(const char *name)
Name the thread this function is called on for the debugger.
Definition: os2.cpp:217
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:37
Signal used for signalling we knowingly want to end the thread.
Definition: thread.h:20