Sese Framework  2.3.0
A cross-platform framework
Loading...
Searching...
No Matches
Thread.h
Go to the documentation of this file.
1// Copyright 2024 libsese
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
23#pragma once
24
25#include "sese/Config.h"
28
29#include <functional>
30#include <thread>
31
32#ifdef __linux__
33#include <sys/syscall.h>
34#include <unistd.h>
35#endif
36
37#ifdef _WIN32
38#include <windows.h>
39#pragma warning(disable : 4251)
40#pragma warning(disable : 4624)
41#endif
42
43namespace sese {
44
46class ThreadInitiateTask final : public InitiateTask {
47public:
48 ThreadInitiateTask() : InitiateTask(__FUNCTION__) {};
49
50 int32_t init() noexcept override;
51
52 int32_t destroy() noexcept override;
53};
54
58class Thread final : public Noncopyable { // GCOVR_EXCL_LINE
59public:
60 using Ptr = std::unique_ptr<Thread>;
61
62 struct RuntimeData;
63
64 explicit Thread(const std::function<void()> &function, const std::string &name = THREAD_DEFAULT_NAME);
65 Thread(Thread &thread);
66 ~Thread() override;
67
68 void start() const;
69 void join() const;
70 void detach() const;
71 [[nodiscard]] bool joinable() const;
72
73 static void run(std::shared_ptr<RuntimeData> data);
74
75 [[nodiscard]] tid_t getTid() const noexcept { return data->id; }
76 [[nodiscard]] const std::string &getThreadName() const noexcept { return this->data->name; }
77
78public:
80 struct RuntimeData {
81 tid_t id = 0;
82
83 std::string name;
84 std::thread th;
85 std::function<void()> function;
86 };
87
88 static tid_t getCurrentThreadId() noexcept;
89 static const char *getCurrentThreadName() noexcept;
90 static void setCurrentThreadAsMain() noexcept;
91 static tid_t getMainThreadId() noexcept;
92
97 static Thread::RuntimeData *getCurrentThreadData() noexcept;
98
99private:
100 static tid_t main_id;
101 std::shared_ptr<RuntimeData> data = nullptr;
102};
103
104} // namespace sese