Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
ThreadPool.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
22#pragma once
23
24#include "sese/Config.h"
26#include "sese/thread/Thread.h"
27
28#include <atomic>
29#include <condition_variable>
30#include <future>
31#include <memory>
32#include <queue>
33#include <string>
34#include <vector>
35
36namespace sese {
37
41class ThreadPool : public Noncopyable {
42public:
43 using Ptr = std::unique_ptr<ThreadPool>;
44
50 explicit ThreadPool(std::string thread_pool_name = THREAD_DEFAULT_NAME, size_t threads = 4);
51 ~ThreadPool() override;
52
53public:
58 void postTask(const std::function<void()> &task);
59
64 void postTask(const std::vector<std::function<void()>> &tasks);
65
73 template<typename FUNCTION, typename... ARGS>
74 void postTaskEx(FUNCTION &&f, ARGS &&...args) {
75 auto bound_function = [func = std::forward<FUNCTION>(f), args = std::make_tuple(std::forward<ARGS>(args)...)]() mutable {
76 std::apply(std::move(func), std::move(args));
77 };
78 this->postTask(std::move(bound_function));
79 }
80
87 template<class RETURN_TYPE>
88 std::shared_future<RETURN_TYPE> postTask(const std::function<RETURN_TYPE()> &tasks);
89
93 void shutdown();
94
95 [[nodiscard]] size_t size() noexcept;
96 [[nodiscard]] bool empty() noexcept;
97 [[nodiscard]] const std::string &getName() const { return name; }
98 [[nodiscard]] size_t getThreads() const { return threads; }
99
100private:
101 std::string name;
102 size_t threads = 0;
103 std::vector<Thread *> threadGroup;
104
106 struct RuntimeData {
107 std::mutex mutex;
108 std::condition_variable conditionVariable;
109 std::queue<std::function<void()>> tasks;
110 std::atomic<bool> isShutdown{false};
111 };
112 std::shared_ptr<RuntimeData> data;
113};
114
115} // namespace sese
116
117// GCOVR_EXCL_START
118
119template<class RETURN_TYPE>
120std::shared_future<RETURN_TYPE> sese::ThreadPool::postTask(const std::function<RETURN_TYPE()> &task) {
127 using TaskPtr = std::shared_ptr<std::packaged_task<RETURN_TYPE()>>;
128 TaskPtr packaged_task = std::make_shared<std::packaged_task<RETURN_TYPE()>>(task);
129 std::shared_future<RETURN_TYPE> future(packaged_task->get_future());
130
131 this->postTask([task = std::move(packaged_task)]() mutable {
132 (*task)();
133 });
134
135 return future;
136}
137
138// GCOVR_EXCL_STOP