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/>.
8 /** @file thread.h Base of all threads. */
15 #include "error_func.h"
16 #include <system_error>
21 * Sleep on the current thread for a defined time.
22 * @param milliseconds Time to sleep for in milliseconds.
24 inline void CSleep(int milliseconds
)
26 std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds
));
30 * Name the thread this function is called on for the debugger.
31 * @param name Name to set for the thread..
33 void SetCurrentThreadName(const char *name
);
38 * @tparam TFn Type of the function to call on the thread.
39 * @tparam TArgs Type of the parameters of the thread function.
40 * @param thr Pointer to a thread object; may be \c nullptr if a detached thread is wanted.
41 * @param name Name of the thread.
42 * @param _Fx Function to call on the thread.
43 * @param _Ax Arguments for the thread function.
44 * @return True if the thread was successfully started, false otherwise.
46 template<class TFn
, class... TArgs
>
47 inline bool StartNewThread(std::thread
*thr
, const char *name
, TFn
&& _Fx
, TArgs
&&... _Ax
)
50 static std::mutex thread_startup_mutex
;
51 std::lock_guard
<std::mutex
> lock(thread_startup_mutex
);
53 std::thread
t([] (const char *name
, TFn
&& F
, TArgs
&&... A
) {
54 /* Delay starting the thread till the main thread is finished
55 * with the administration. This prevent race-conditions on
58 std::lock_guard
<std::mutex
> lock(thread_startup_mutex
);
61 SetCurrentThreadName(name
);
62 CrashLog::InitThread();
64 /* Call user function with the given arguments. */
66 } catch (std::exception
&e
) {
67 FatalError("Unhandled exception in {} thread: {}", name
, e
.what());
71 }, name
, std::forward
<TFn
>(_Fx
), std::forward
<TArgs
>(_Ax
)...);
80 } catch (const std::system_error
&e
) {
81 /* Something went wrong, the system we are running on might not support threads. */
82 Debug(misc
, 1, "Can't create thread '{}': {}", name
, e
.what());