Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
Thread.h
浏览该文件的文档.
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
67 void start();
68 void join();
69 void detach();
70 [[nodiscard]] bool joinable() const;
71
72 static void run(std::shared_ptr<RuntimeData> data);
73
74 [[nodiscard]] tid_t getTid() const noexcept { return data->id; }
75 [[nodiscard]] const std::string &getThreadName() const noexcept { return this->data->name; }
76
77public:
79 struct RuntimeData {
80 tid_t id = 0;
81
82 std::string name;
83 std::thread th;
84 std::function<void()> function;
85 };
86
87 static tid_t getCurrentThreadId() noexcept;
88 static const char *getCurrentThreadName() noexcept;
89 static void setCurrentThreadAsMain() noexcept;
90 static tid_t getMainThreadId() noexcept;
91
96 static Thread::RuntimeData *getCurrentThreadData() noexcept;
97
98private:
99 static tid_t main_id;
100 std::shared_ptr<RuntimeData> data = nullptr;
101};
102
103} // namespace sese