OpenTTD Source  14.0-beta3
thread.h
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
10 #ifndef THREAD_H
11 #define THREAD_H
12 
13 #include "debug.h"
14 #include "crashlog.h"
15 #include <system_error>
16 #include <thread>
17 #include <mutex>
18 
23 inline void CSleep(int milliseconds)
24 {
25  std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
26 }
27 
32 void SetCurrentThreadName(const char *name);
33 
34 
45 template<class TFn, class... TArgs>
46 inline bool StartNewThread(std::thread *thr, const char *name, TFn&& _Fx, TArgs&&... _Ax)
47 {
48  try {
49  static std::mutex thread_startup_mutex;
50  std::lock_guard<std::mutex> lock(thread_startup_mutex);
51 
52  std::thread t([] (const char *name, TFn&& F, TArgs&&... A) {
53  /* Delay starting the thread till the main thread is finished
54  * with the administration. This prevent race-conditions on
55  * startup. */
56  {
57  std::lock_guard<std::mutex> lock(thread_startup_mutex);
58  }
59 
62  try {
63  /* Call user function with the given arguments. */
64  F(A...);
65  } catch (...) {
66  NOT_REACHED();
67  }
68  }, name, std::forward<TFn>(_Fx), std::forward<TArgs>(_Ax)...);
69 
70  if (thr != nullptr) {
71  *thr = std::move(t);
72  } else {
73  t.detach();
74  }
75 
76  return true;
77  } catch (const std::system_error &e) {
78  /* Something went wrong, the system we are running on might not support threads. */
79  Debug(misc, 1, "Can't create thread '{}': {}", name, e.what());
80  }
81 
82  return false;
83 }
84 
85 #endif /* THREAD_H */
SetCurrentThreadName
void SetCurrentThreadName(const char *name)
Name the thread this function is called on for the debugger.
Definition: win32.cpp:675
CSleep
void CSleep(int milliseconds)
Sleep on the current thread for a defined time.
Definition: thread.h:23
lock
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:35
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
CrashLog::InitThread
static void InitThread()
Prepare crash log handler for a newly started thread.
Definition: crashlog_osx.cpp:238
StartNewThread
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:46
crashlog.h
debug.h