Fix: Stopped ships shouldn't block depots (#8578)
[openttd-github.git] / src / thread.h
blobf4a16d4e0da660ef48030df6b89f4a1007edfed1
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 */
8 /** @file thread.h Base of all threads. */
10 #ifndef THREAD_H
11 #define THREAD_H
13 #include "debug.h"
14 #include <system_error>
15 #include <thread>
17 /** Signal used for signalling we knowingly want to end the thread. */
18 class OTTDThreadExitSignal { };
21 /**
22 * Sleep on the current thread for a defined time.
23 * @param milliseconds Time to sleep for in milliseconds.
25 inline void CSleep(int milliseconds)
27 std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
30 /**
31 * Name the thread this function is called on for the debugger.
32 * @param name Name to set for the thread..
34 void SetCurrentThreadName(const char *name);
37 /**
38 * Start a new thread.
39 * @tparam TFn Type of the function to call on the thread.
40 * @tparam TArgs Type of the parameters of the thread function.
41 * @param thr Pointer to a thread object; may be \c nullptr if a detached thread is wanted.
42 * @param name Name of the thread.
43 * @param _Fx Function to call on the thread.
44 * @param _Ax Arguments for the thread function.
45 * @return True if the thread was successfully started, false otherwise.
47 template<class TFn, class... TArgs>
48 inline bool StartNewThread(std::thread *thr, const char *name, TFn&& _Fx, TArgs&&... _Ax)
50 #ifndef NO_THREADS
51 try {
52 std::thread t([] (const char *name, TFn&& F, TArgs&&... A) {
53 SetCurrentThreadName(name);
54 try {
55 /* Call user function with the given arguments. */
56 F(A...);
57 } catch (OTTDThreadExitSignal&) {
58 } catch (...) {
59 NOT_REACHED();
61 }, name, std::forward<TFn>(_Fx), std::forward<TArgs>(_Ax)...);
63 if (thr != nullptr) {
64 *thr = std::move(t);
65 } else {
66 t.detach();
69 return true;
70 } catch (const std::system_error& e) {
71 /* Something went wrong, the system we are running on might not support threads. */
72 DEBUG(misc, 1, "Can't create thread '%s': %s", name, e.what());
74 #endif
76 return false;
79 #endif /* THREAD_H */