Sese Framework  x.y.z
A cross-platform framework
载入中...
搜索中...
未找到
GlobalThreadPool.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
19
20#pragma once
21
22#include <sese/Config.h>
24#include <sese/util/Singleton.h>
25
26namespace sese {
27
30public:
31 static void postTask(const std::function<void()> &func);
32
33 template<class RETURN_TYPE>
34 static std::shared_future<RETURN_TYPE> postTask(const std::function<RETURN_TYPE()> &func);
35
36#ifdef SESE_PLATFORM_WINDOWS
37private:
38 struct Task1 {
39 std::function<void()> function;
40 };
41
42 template<class RETURN_TYPE>
43 struct Task2 {
44 std::packaged_task<RETURN_TYPE()> packagedTask;
45 };
46
47 static DWORD WINAPI taskRunner1(LPVOID lp_param);
48
49 template<class RETURN_TYPE>
50 static DWORD WINAPI taskRunner2(LPVOID lp_parma);
51#else
52private:
54#endif
55};
56} // namespace sese
57
58#ifdef SESE_PLATFORM_WINDOWS
59
60template<class RETURN_TYPE>
61std::shared_future<RETURN_TYPE> sese::GlobalThreadPool::postTask(const std::function<RETURN_TYPE()> &func) {
62 auto task2 = new Task2<RETURN_TYPE>();
63 auto packaged_task = std::packaged_task<RETURN_TYPE()>(func);
64 std::shared_future<RETURN_TYPE> future(packaged_task.get_future());
65 task2->packagedTask = std::move(packaged_task);
66 QueueUserWorkItem(taskRunner2<RETURN_TYPE>, task2, WT_EXECUTEDEFAULT);
67 return future;
68}
69
70template<class RETURN_TYPE>
71DWORD sese::GlobalThreadPool::taskRunner2(LPVOID lp_parma) {
72 auto task2 = static_cast<Task2<RETURN_TYPE> *>(lp_parma);
73 task2->packagedTask();
74 delete task2;
75 return 0;
76}
77
78#else
79
80template<class ReturnType>
81std::shared_future<ReturnType> sese::GlobalThreadPool::postTask(const std::function<ReturnType()> &func) {
82 auto pool = globalThreadPool.getInstance();
83 return pool->postTask<ReturnType>(func);
84}
85
86#endif